【问题标题】:How to convert JsonArray to Hashmap如何将 JsonArray 转换为 Hashmap
【发布时间】:2016-02-09 07:41:47
【问题描述】:

我已经能够从 json 字符串中获取 jsonarray,但不知道如何将其放入 Hashmap 中,其中包含显示货物类型的字符串和显示数量的整数。

字符串:

"cargo":[   
    {"type":"Coals","amount":75309},        
    {"type":"Chemicals","amount":54454},        
    {"type":"Food","amount":31659},     
    {"type":"Oil","amount":18378}
]

【问题讨论】:

  • 不抱歉,已经尝试过,有些方法似乎不适用于该示例
  • 你尝试了什么,结果如何?
  • 我尝试了您提供给我的链接中的代码。但是“JSONObject”和“optJSONObject”无法解析,可能是因为我使用了 javax.json 库,而那家伙使用了另一个库?

标签: java arrays json


【解决方案1】:

这为我解决了问题:

JsonArray jsoncargo = jsonObject.getJsonArray("cargo");

Map<String, Integer> cargo = new HashMap<>();
for (int i = 0; i < jsoncargo.size(); i++) {            
    String type = jsoncargo.getJsonObject(i).getString("type");
    Integer amount = jsoncargo.getJsonObject(i).getInt("amount");
    cargo.put(type, amount);
}

【讨论】:

  • 错误@getJsonObject 方法
【解决方案2】:

尝试创建一个新的 HashMap,并遍历 JSONArray,将每个元素添加到 hashmap。

JSONArray allCargo = jsonObject.getJsonArray("cargo");

HashMap<String, String> hm = new HashMap();

for(Object cargo : allCargo) {
    LinkedHashMap lhm = (LinkedHashMap) cargo;
    hm.put((String)lhm.get("type"), (String)lhm.get("amount"));
}

【讨论】:

  • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 2011-11-03
  • 2014-05-06
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多