我有一個JSONArray,在下面的格式有數據:轉換JSONArray到HashMap和匹配
[[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}],
[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]]
我想把數據到HashMap中,這樣的事情:
"IN":10
"US":20
"IN":10
"US":20
基本上,我正在做一個計數匹配,以確保一個類型的所有Country
具有相同的count
。
這裏是我試過了,JSONArray存儲爲myArray
:
Map<String, Integer> cargo = new HashMap<>();
for (int j = 0; j < myArray.length(); j++) {
String country = myArray.getJSONObject(j).getString("country");
Integer count = myArray.getJSONObject(j).getInt("count");
cargo.put(country, count);
}
,但我得到JSONArray[0] is not a JSONObject
錯誤。
感謝,
編輯:這讓我得到它的映射。
`
Map<String, Integer> cargo = new HashMap<>();
for (int j = 0; j < myArray.length(); j++) {
for (int k = 0; k < myArray.getJSONArray(j).length(); k++) {
String country = myArray.getJSONArray(j).getJSONObject(k).getString("country");
Integer count = myArray.getJSONArray(j).getJSONObject(k).getInt("count");
cargo.put(country, count);
}
`
你的json是一個數組數組,所以你需要在每個數組上添加一個循環。 –