I have a JSONArray that has data in following format :
[[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}],
[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]]
I want to put the data to an HashMap, something like this :
"IN":10
"US":20
"IN":10
"US":20
Basically, I am doing a count match so as to ensure all Country of a type have same count.
Here is what I tried, JSONArray is stored as 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);
}
But I get JSONArray[0] is not a JSONObject error.
Thanks,
Edit : This helped me get it to map.
`
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);
}
`