JSONArray 操作

JSONArray Manipulation

在我的代码中我创建了一个 JSONArray object.And 添加两个 JSONObjects 到 JSONArray object.I 我正在使用 json-simple-1.1.jar.My 代码是

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

我的问题是如何从 JSONArray 对象 ("ja") 中获取第二个对象 ("jo1") 的年龄值。我试过 ja.get(1).get("Age")。没有work.Can任何人提前建议idea.Thanks。

尝试以下操作:

for(int i=0;i<ja.size();i++)
      System.out.println(ja.getJSONObject(i).get("Age"));

因为您使用的是 json-简单的 jar。没有单独的方法来获取 JSONObject。

首先你需要将该对象转换为JSONObject,然后你可以做进一步的处理。

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