2017-09-06 93 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是一个数组的数组,所以你需要在每个阵列一个额外的循环。