Java 如何将 JsonArray 转换为 Hashmap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33595941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Howto convert JsonArray to Hashmap
提问by Zoef
I've been able to get a jsonarray from a json string, but don't know how to put it in a Hashmap with a String that shows the type of cargo and an Integer showing the amount.
我已经能够从一个 json 字符串中获取一个 jsonarray,但不知道如何将它放入一个带有显示货物类型的字符串和一个显示数量的整数的 Hashmap 中。
The string:
字符串:
"cargo":[
{"type":"Coals","amount":75309},
{"type":"Chemicals","amount":54454},
{"type":"Food","amount":31659},
{"type":"Oil","amount":18378}
]
回答by Zoef
This fixed it for me:
这为我修复了它:
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);
}
回答by Satya
Try creating a new HashMap, and loop through the JSONArray, adding each element to the hashmap.
尝试创建一个新的 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"));
}