【发布时间】:2018-02-14 18:44:22
【问题描述】:
我有一个 JSONArray,其中包含以下格式的数据:
[[{ "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 是一个数组数组,因此您需要对每个数组进行额外循环。