转换JSONArray到HashMap和匹配
问题描述:
我有一个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);
}
`
答
你JSONArray[0]
等于
[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]
所以不是JSONObject
的确,你需要做一个for
一个for
里面,遍历每个对象。
for (int j = 0; j < myArray.length(); j++) {
for (int k = 0; k < myArray[j].length(); k++) {
String country = myArray[j].getJSONObject(k).getString("country");
Integer count = myArray[j].getJSONObject(k).getInt("count");
cargo.put(country, count);
}
}
答
你JSON是一个数组的数组,所以你需要在每个阵列一个额外的循环。
你的json是一个数组数组,所以你需要在每个数组上添加一个循环。 –