我有一个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);
  }


`

最佳答案

您的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);
  }
}

09-30 15:19
查看更多