Search code examples
javajsonjson-simple

JSONArray Manipulation


in my code i created a JSONArray object.And adding two JSONObjects to the JSONArray object.I am using json-simple-1.1.jar.My code is

package jsonjava;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
public class JsonJava {
public static void main(String[] args) 
{
    JSONArray ja=new JSONArray();
    JSONObject jo=new JSONObject();
    jo.put("name","prem");
    jo.put("id", 2012103575);
    jo.put("Age",20);
    ja.add(jo);
    JSONObject jo1=new JSONObject();
    jo1.put("name","prem");
    jo1.put("id", 2012103575);
    jo1.put("Age",21);
    ja.add(jo1);
    for(int i=0;i<ja.size();i++)
      System.out.println(ja.get(i));
}

My Question is how to get the Age value from second object("jo1") from JSONArray object ("ja").I tried ja.get(1).get("Age").It doesn't work.Can any one suggest idea.Thanks in advance.


Solution

  • Since you are using json-simple jar. There is no separate method to get JSONObject.

    First You need to cast that object to JSONObject, then you can do further processing.

    for(int i=0;i<ja.size();i++){
        JSONObject json=(JSONObject) ja.get(i);
        System.out.println(json.get("Age"));
    }