Santhosh
Santhosh

Reputation: 8197

Iterate Array of JSON objects

I am using org.json.simple library to construct JSONArray of JSONObject. So my structure looks like

c= [
  {
    "name":"test",
    "age":1
  },
  {
   "name":"test",
   "age":1
   }
]

To iterate the array in java, I tried

for (int i = 0; i < c.size(); i++) {
    JSONObject obj = (JSONObject) c.get(i);
    System.out.println(obj.get("name"));        
}

It printed null, but when tried to print the obj.toString, it prints the JSON string as expected.

I am using org.json.simple jar, so cannot use the methods defined org.json.JSONArray or org.json.JSONObject.

Any ideas to get the values from the object with their key?

Upvotes: 3

Views: 7877

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

You can iterate over the JSONArray elements using an Iterator, like this:

    //arr is your JSONArray here
    Iterator<Object> iterator = arr.iterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if(obj instanceof JSONObject) {
             System.out.println(obj.get("name"));
        }
    }

It uses org.json.simple.JSONObject and org.json.simple.JSONArray.

Upvotes: 2

Tagir Valeev
Tagir Valeev

Reputation: 100219

Your code is absolutely correct, it works fine with org.json.simple:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonTest {
    public static void main(String[] args) throws ParseException {
        JSONArray c = (JSONArray) new JSONParser()
                .parse("[ { \"name\":\"test\", \"age\":1 }, "
                        + "{ \"name\":\"test\", \"age\":1 } ]");
        for (int i = 0; i < c.size(); i++) {
            JSONObject obj = (JSONObject) c.get(i);
            System.out.println(obj.get("name"));        
        }
    }
}

It outputs:

test
test

Check how input JSONArray was created. It's possible that there's something different inside it. For example, it's possible that you have non-printable character in key name, so you don't see it when using c.toString(), but obj.get("name") fails.

Upvotes: 5

Atul O Holic
Atul O Holic

Reputation: 6792

use the following snippet to parse the JsonArray.

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String name = jsonobject.getString("name");
    int age = jsonobject.getInt("age");
}

Hope it helps.

Credits - https://stackoverflow.com/a/18977257/3036759

Upvotes: 1

Related Questions