2015-11-08 159 views
3

我已經能夠得到一個JSON字符串一個jsonarray,但不知道如何把它放在一個HashMap和String顯示貨物和整數出量的類型。HOWTO轉換JsonArray到HashMap的

字符串:

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

可能這個鏈接可以幫助http://stackoverflow.com/questions/4307118/jsonarray-to-hashmap – Shriram

+0

沒有對不起,已經試過那個,有些方法似乎不適用於這個例子 – Zoef

+0

你嘗試了什麼,結果是什麼? – BrunoLevy

回答

2

這個固定對我來說:

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