本文介绍了在java中用gson解析数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

c> WebsiteResults 类必须与JSON相匹配或者使用 @SerializedName 注释告诉Gson它是什么:



更改:

 私人列表< univ>结果; 

到:

 私人列表< univ>大学; 

或:

  @SerializedName(univ)
private List< univ>结果;

事实上,您为 univ class也令人困惑;不要这样做。类名应以大写字母开头。


i am getting following data from php script..

  {"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"}

    }]}

i want to parse this using GSON.

i have written following class:

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 + "]"; }
    }

}

i want to get array of univ_id and univ_name.

but i am getting results = null.can someone help to explain what i have done wrong.

WebsiteResults results = new Gson().fromJson(reader, WebsiteResults.class);
String errno = results.getErrorNo();
String result = results.toString();
解决方案

The name of your field in your WebsiteResults class has to match the JSON or have the @SerializedName annotation to tell Gson what it is:

Change:

private List<univ> results;

to:

private List<univ> univ;

or:

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

The fact that you've used a lowercase name for your univ class makes that confusing as well; don't do that. Class names should start with uppercase.

这篇关于在java中用gson解析数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:45
查看更多