1

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

`

1
  • Your json is an array of arrays so you need an extra loop over each array. Commented Sep 6, 2017 at 10:12

2 Answers 2

1

Your JSONArray[0] equals to

[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]

So not an JSONObject indeed, you need to do a for inside a for, to iterate every object.


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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Well, I tried this, But for the second loop, I get the type of the expression should be an array type but it resolved to JSONArray.
So find a way to loop an JSONArray :)
Ya. I found. Updated the question.
0

Your json is an array of arrays so you need an extra loop over each array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.