【问题标题】:Converting JSONArray to HashMap and Matching将 JSONArray 转换为 HashMap 并进行匹配
【发布时间】: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 是一个数组数组,因此您需要对每个数组进行额外循环。

标签: java arrays json hashmap


【解决方案1】:

您的 json 是一个数组数组,因此您需要对每个数组进行额外循环。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 好吧,我试过了,但是对于第二个循环,我得到了the type of the expression should be an array type but it resolved to JSONArray
    • 所以想办法循环一个 JSONArray :)
    • 是的。我发现。更新了问题。
    猜你喜欢
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2013-11-15
    • 2013-06-06
    相关资源
    最近更新 更多