2011-12-29 205 views
2

多個對象在此刻,我可以正確地分析JSON是這樣的:解析與GSON

"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
{ 
"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 ( );

+0

謝謝你的回答!但是它絕對拒絕從對象類中獲取Assignments。 getAssignments無法解析,因爲它在Objectclass中被明確聲明,所以很奇怪。 – MaikelS 2011-12-29 12:20:30

+0

清理項目,並在公共 – 2011-12-29 12:25:35

+0

還追加「{」「}」在您的JSON字符串額外的括號 – 2011-12-29 12:26:13

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

+1一個確切的答案。 – 2011-12-29 11:31:35

+0

@MaikelS爲什麼不使用和內置功能,而是使用外部庫來解析JSON。 – 2011-12-29 11:37:00

+0

我想使用GSON,它要簡單得多。事實上,我沒有三個字符串,但數百個字符串。我用這個例子來簡化我的問題。而且說實話:你不能擊敗這樣的: 分配數據=新GSON()fromJson(JSON,Assignment.class); – MaikelS 2011-12-29 11:38:54