使用GSON解析多个对象

时间:2011-12-29 11:15:32

标签: android json gson

目前我可以正确解析这样的JSON:

"assignments:[{"
    + "'id': '111',"
    + "'erporder_erpid' : '132',"
    + "'dtStart' : '10:00 12-12-12',"
+ "}]"; 

与GSON合作。但我不知道解析多个对象的适当方法,如:

"assignments:[{"
    + "'id': '111',"
    + "'erporder_erpid' : '132',"
    + "'dtStart' : '10:00 12-12-12',"
+ "},"
+ "{"
    + "'id': '111',"
    + "'erporder_erpid' : '132',"
    + "'dtStart' : '10:00 12-12-12',"
+ "}]"

我正确设置了Javabean。

2 个答案:

答案 0 :(得分:3)

您可以使用以下方法:

JSONArray outerArr = new JSONArray("assignments"); 
for(int ictr=0;ictr<outerArr.length;ictr++)
{
        JSONObject obj =outerArr.getJSONObject(ictr);
        String id=obj.getString("id");
        String erporder_erpid=obj.getString("erporder_erpid");
        String dtStart=obj.getString("dtStart");
}

希望这对你有所帮助。

答案 1 :(得分:3)

{
"assignments:[{"
        + "'id': '111',"
        + "'erporder_erpid' : '132',"
        + "'dtStart' : '10:00 12-12-12',"
    + "},"
    + "{"
        + "'id': '111',"
        + "'erporder_erpid' : '132',"
        + "'dtStart' : '10:00 12-12-12',"
    + "}]"
}

Objectclass.java

public class takeData {
public List<assignmentsData> assignments;


    public List<assignmentsData> getAssignments() {
        return assignments;
    }

    public void setAssignments(List<assignmentsData> assignments) {
        this.assignments = assignments;
    }
}

assignmentsData.java

public class assignmentsData {
    public String id="";
    public String erporder_erpid="";
    public String dtStart="";


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getErporder_erpid() {
        return erporder_erpid;
    }

    public void setErporder_erpid(String erporder_erpid) {
        this.erporder_erpid = erporder_erpid;
    }

    public String getDtStart() {
        return dtStart;
    }

    public void setDtStart(String dtStart) {
        this.dtStart = dtStart;
    }
}

parsingClass.java

Gson mGson= new Gson();
Objectclass mObjectclass=gson.fromJson(jsonString, Objectclass.class);

访问: mObjectclass.getAssignments.get(0).getId();