3

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?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Santhosh
  • 8,181
  • 4
  • 29
  • 56

3 Answers3

5

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
2

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.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

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

Community
  • 1
  • 1
Atul O Holic
  • 6,692
  • 4
  • 39
  • 74
  • 1
    no this will not work as mentioned in the question , am using `org.simple.json` JSONArray. it doesnt have `length()` method – Santhosh Jun 25 '15 at 09:56