我从php脚本中获取以下数据..
{"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 :(得分:0)
WebsiteResults
类中字段的名称必须与JSON匹配或具有@SerializedName
注释才能告诉Gson它是什么:
变化:
private List<univ> results;
为:
private List<univ> univ;
或:
@SerializedName("univ")
private List<univ> results;
您使用univ
类的小写名称这一事实也让人感到困惑;不要那样做。类名应以大写字母开头。