2013-03-08 110 views
0

我得到以下從PHP腳本數據..在GSON解析陣列中的Java

{"errorno":"fe_200","message":"successful","univ":[{"univ_id":"1","univ_name":"abc","slug":"uptu","thumb":"http:\/\/www.fs.com\/notes\/img\/uptu.gif","table_prefix":"uptu"},{"univ_id":"2","univ_name":"def","slug":"gtu","thumb":"http:\/\/www.fs.com\/notes\/img\/gtu.gif","table_prefix":"gtu"}, 
    {"univ_id":"3","univ_name":"jvc university","slug":"jntu","thumb":"http:\/\/www.fs.com\/notes\/img\/jntu.gif","table_prefix":"jntu"} 

    }]} 

我要分析此使用GSON。

我寫了下面的類:

class WebsiteResults { 

    public WebsiteResults() {} 

    private String errorno; 
    private String message; 
    private List<univ> results; 
    // other attributes 

    public String getErrorNo() { 
    return errorno; 
    } 
    public String getMessage() { 
     return message; 
     } 
    public List<univ> getResults() { return results; } 
    public void setErrorNo(String errorno) { 
     this.errorno = errorno; 
     } 
    public void setMessage(String message) { 
    this.message = message; 
    } 

    public void setResults(List<univ> results) { this.results = results; } 
    public String toString() { return "Results[" + results + "]";} 


    static class univ { 
     private String univ_id; 
     private String univ_name; 
     public String getUnivID() { return univ_id; } 
     public String getUnivName() { return univ_name; } 
     public void setUnivID(String univ_id) { this.univ_id = univ_id; } 
     public void setUnivName(String univ_name) { this.univ_name = univ_name; } 
     public String toString() { return "Result[id:" + univ_id +",title:" + univ_name + "]"; } 
    } 

} 

我想univ_id和univ_name的陣列。

但我得到的結果= null。 有人可以幫助解釋我做錯了什麼。

WebsiteResults results = new Gson().fromJson(reader, WebsiteResults.class); 
String errno = results.getErrorNo(); 
String result = results.toString(); 
+0

errno我越來越好了 – Sunny 2013-03-08 19:38:34

回答

0

你的領域在你WebsiteResults類的名稱必須符合JSON或有@SerializedName註解告訴GSON它是什麼:

變化:

private List<univ> results; 

到:

private List<univ> univ; 

或者:

@SerializedName("univ") 
private List<univ> results; 

您爲univ類使用了一個小寫字母名稱的事實也令人困惑;不要這樣做。類名應以大寫字母開頭。

+0

非常感謝Brian .. :) – Sunny 2013-03-09 06:37:30

+0

我以爲class name應該和JSON格式中提到的一樣..再次感謝.. – Sunny 2013-03-09 06:38:11