【问题标题】:Gson how to deserialise null object propertyGson如何反序列化空对象属性
【发布时间】:2012-09-06 19:10:21
【问题描述】:

我有一些 json,有一系列看起来像这样的条目(我已将其简化为专注于相关问题,这就是为什么它看起来有点多余):

{"name":"ISPC 塞舌尔","company":{"name":"ISPC 塞舌尔","id":3427640}}

但有时公司属性设置为空:

{"name":"京都威斯汀都酒店", "company":null}

我已经这样定义了我的类(对不起,公共访问修饰符,当我得到这段代码工作时会改变这些:)):

class Entry {
  public String name=;
  public Company company;
  public String toString() {
      return  name + ";" + company;
  }
}

class Company {
    public String name;
    public int id;
    public String toString() {
        return "Company: " + name;
    }
}

在我的代码中,我尝试使用 gson 反序列化包含在名为 output 的变量中的 JSON:

while ((output = br.readLine()) != null) {
    Gson gson = new Gson();
    Reply reply = gson.fromJson(output, Reply.class); 
    Entry[] entries = reply.entries;
    for (int i=0; i < entries.length; i++) {
        System.out.print(entries[i]+ "\n") ;
    }
}

当按照 JSON 中的第一个示例填充公司元素时,这可以正常工作:

ISPC 塞舌尔;公司:ISPC 塞舌尔

但是,如果元素没有像第二个示例中那样填充,我会得到以下输出:

京都威斯汀都酒店;空

我想要的是以下输出:

京都威斯汀都酒店;公司:无

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    CompanytoString() 表示由 Company 对象控制,因此如果 Company 对象为空,则无法获得所需的表示。唯一的方法是在您的Entry 类'toString() 中包含以下内容:

    class Entry {
      ...
      ...
    
        public String toString() {
            return  name + "; " + (company != null ? company : "Company: null");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多