【问题标题】:GSON toJson() method returns null for a POJOGSON toJson() 方法为 POJO 返回 null
【发布时间】:2018-12-11 11:47:40
【问题描述】:

这是我的 POJO 类

public class ResourceRecord {

    public ResourceRecord() {}

    public String name;
    public Integer ttl;
    public String type;
    public String rr;

    @SerializedName("class")
    public String dnsClass;

}

这是序列化:

ResourceRecord rr = new ResourceRecord() {
    {
        name = "8.8.8.8";
        dnsClass = "IN";
        ttl = 600;
        rr = "0431shangmao.com.";
        type = "A";
    }
};

String rrStr = new Gson().toJson(rr);

显然,rrStr 得到 null。为什么?

我尝试用 @Expose 注释字段,但结果保持不变。

更新: 我改为构造:

ResourceRecord rr = new ResourceRecord("8.8.8.8", 900,"A","1.dnstest.netshade.net.", "IN");

它成功了。

【问题讨论】:

    标签: java json serialization gson


    【解决方案1】:

    它不起作用的原因是因为您在使用花括号进行实例化时创建了ResourceRecord 的匿名内部类:

    ResourceRecord rr = new ResourceRecord() {
          {
              name = "8.8.8.8";
              dnsClass = "IN";
              ttl = 600;
              rr = "0431shangmao.com.";
              type = "A";
          }
      };
    

    而且 Gson 不支持序列化匿名子类。

    【讨论】:

      【解决方案2】:

      试试这个,

      Gson gson = new GsonBuilder().create(); String json = gson.toJson(obj);

      obj 是 pojo 类的对象

      【讨论】:

        猜你喜欢
        • 2017-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多