Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Array of JSON objects

Tags:

java

json

arrays

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?

like image 507
Santhosh Avatar asked Mar 28 '26 15:03

Santhosh


1 Answers

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.

like image 183
Tagir Valeev Avatar answered Mar 31 '26 04:03

Tagir Valeev