2017-09-06 88 views
1

我有一個JSONArray,在下面的格式有數據:轉換JSONArray到HashMap和匹配

[[{ "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); 
    } 

`

+0

你的json是一個數組數組,所以你需要在每個數組上添加一個循環。 –

回答

1

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

嗯,我試過了,但是對於第二個循環,我得到'表達式的類型應該是數組類型,但是它解析爲JSONArray'。 – AYa

+0

所以找一個方法來循環一個JSONArray :) –

+1

Ya。我發現。更新了問題。 – AYa

0

你JSON是一個數組的數組,所以你需要在每個陣列一個額外的循環。