0

我从 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();
4

1 回答 1

0

类中的字段名称WebsiteResults必须与 JSON 匹配或具有@SerializedName注释以告诉 Gson 它是什么:

改变:

private List<univ> results;

到:

private List<univ> univ;

或者:

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

您为班级使用小写名称的事实也使您univ感到困惑;不要那样做。类名应以大写开头。

于 2013-03-08T20:15:31.350 回答