Gson 自动过滤null 解决方案。

对于许久不用的东西,容易忘记。百度许久,也未能找到自己所要。

从今日起,有些东西就记载下来,不仅方便自己,希望能帮到他人吧。

    private String aviType = "0";
    private String trace = "0";
    private String isFirstTransfer = "1";
    private String mty = "0140";
    private String respcode = null;

    private OpRecord opRecord;

    private class OpRecord {
        private String createTime = getData();

        private String createUserCode = "00000075";

        private String id = null;

        private String waybillNo;

        private int opCode = 182;

        public OpRecord() {
        }

        public void setWaybillNo(String waybillNo) {
            this.waybillNo = waybillNo;
        }
    }

将类作为JSON输入。

  public String getParams(String waybillNo) {
        Gson gson = new Gson();   
        return gson.toJson(this);
    }

输出打印结果:

{
"aviType":"0",
"trace":"0",
"isFirstTransfer":"1",
"mty":"0140",
"opRecord":{
    "createTime":"2018-07-30 14:01:02.632",
    "createUserCode":"00000075",
    "opCode":182
    }
}

装换成Json 是没有任何问题,但不是我想要的結果,缺少属性:

//属性1
  private String respcode = null;
 //属性2
  private String id = null;

想要的JSON结果:

{
"aviType":"0",
"trace":"0",
"isFirstTransfer":"1",
"mty":"0140",
"respcode":null,
"opRecord":{
    "createTime":"2018-07-30 14:04:43.961",
    "id":null,
    "waybillNo":"899931211861",
    "opCode":182
}

为什么Gson会自动过滤null呢,查看源码边知道,new Gson() 自动序列化,导致过滤null。

  this.serializationContext = new JsonSerializationContext() {
            public JsonElement serialize(Object src) {
                return Gson.this.toJsonTree(src);
            }

            public JsonElement serialize(Object src, Type typeOfSrc) {
                return Gson.this.toJsonTree(src, typeOfSrc);
            }
        };

解决方法:

找到问题所在,那我不序列化就不ok吗?可是却没有 new Gson(false),new Gson(null)等,类似这样的构造器。
不过却又另一种方法获取到Gson对象。

  public Gson create() {
        List<TypeAdapterFactory> factories = new ArrayList();
        factories.addAll(this.factories);
        Collections.reverse(factories);
        factories.addAll(this.hierarchyFactories);
        this.addTypeAdaptersForDate(this.datePattern, this.dateStyle, this.timeStyle, factories);
         return new Gson(this.excluder,
                this.fieldNamingPolicy, 
                this.instanceCreators, 
                this.serializeNulls, 
                this.complexMapKeySerialization, 
                this.generateNonExecutableJson, 
                this.escapeHtmlChars,
                this.prettyPrinting, 
                this.serializeSpecialFloatingPointValues,
                this.longSerializationPolicy, 
                factories);
    }

this.serializeNulls,这个属性便是序列化了。让其为null这个属性便可以了。

 GsonBuilder gsonbuilder = new GsonBuilder();
 gsonbuilder.serializeNulls();
 Gson gson = gsonbuilder.create();

这样就获取到了,未经过序列化的Gson。

猜你喜欢

转载自blog.csdn.net/weixin_39923324/article/details/81284358
今日推荐