java中jsonObject轉化為Map
阿新 • • 發佈:2019-01-23
public static void main(String[] args) {
final String str = "{\"45\":[119],\"44\":[119,118,117]}";
final Map<Integer,List<Integer>> label2Ids = new HashMap<Integer,List<Integer>>();
JSONObject labelObj = new JSONObject(str);
if (labelObj != null) {
Iterator<String> it = labelObj.keys();
while (it.hasNext()) {
List<Integer> baseIdList = new ArrayList<Integer>();
final String key = (String) it.next();
JSONArray baseIds = labelObj.getJSONArray(key);
//第一個輸出
System.out.println("key = " + key + ",baseIds = " + baseIds);
final int baseIdCnt = ((baseIds != null) ? baseIds.length() : 0);
if (baseIdCnt > 0) {
for (int i = 0; i < baseIdCnt; i ++) {
baseIdList.add(baseIds.getInt(i));
}
}
label2Ids.put(Integer.parseInt(key), baseIdList);
}
//第二個輸出
System.out.println("label2Ids = " + label2Ids.toString());
}
}
列印結果如下:
key = 44,baseIds = [119,118,117]
key = 45,baseIds = [119]
label2Ids = {44=[119, 118, 117], 45=[119]}
final String str = "{\"45\":[119],\"44\":[119,118,117]}";
final Map<Integer,List<Integer>> label2Ids = new HashMap<Integer,List<Integer>>();
JSONObject labelObj = new JSONObject(str);
if (labelObj != null) {
Iterator<String> it = labelObj.keys();
while (it.hasNext()) {
List<Integer> baseIdList = new ArrayList<Integer>();
final String key = (String) it.next();
JSONArray baseIds = labelObj.getJSONArray(key);
//第一個輸出
System.out.println("key = " + key + ",baseIds = " + baseIds);
final int baseIdCnt = ((baseIds != null) ? baseIds.length() : 0);
if (baseIdCnt > 0) {
for (int i = 0; i < baseIdCnt; i ++) {
baseIdList.add(baseIds.getInt(i));
}
}
label2Ids.put(Integer.parseInt(key), baseIdList);
}
//第二個輸出
System.out.println("label2Ids = " + label2Ids.toString());
}
}
列印結果如下:
key = 44,baseIds = [119,118,117]
key = 45,baseIds = [119]
label2Ids = {44=[119, 118, 117], 45=[119]}