简体   繁体   English

使用GSON序列化/反序列化json / object时的默认值

[英]default value while serialize/deserialize json/object using GSON

I am using GSON for serialize and deserialize JSON/JAva Object for one of my application. 我正在使用GSON对我的应用程序之一进行序列化和反序列化JSON / JAva对象。 I am using serializeNulls as some of my value need to be send as null to web service while some I don't want to be NULL. 我正在使用serializeNulls,因为一些我的值需要作为null发送到Web服务,而另一些我不想为NULL。 So what I tried in my setter/getter for which I don't need null that I have check that value is null or not, if its null then set the "" blank for it. 因此,在我不需要设置为null的setter / getter中尝试了什么,我已经检查了该值是否为null,如果其值为null,则为其设置“”空白。 But still when I am deserializing my object to json using gson.toJson() method its giving me null value for those. 但是仍然当我使用gson.toJson()方法将对象反序列化为json时,它为我提供了null值。

private String mID;

public void setId(final String id) {
    if(id == null) {
        id = "";
    }
    mID = id;
}

public String getId() {
    if(mID == null) {
        mID = "";
    }
    return mID;
}

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

Any idea how can i avoid null for some of the fields and set blank "" using setter/getter method or some other way. 我不知道如何避免某些字段为null并使用setter / getter方法或其他方式设置空白“”。

You can do it using default value of mID and proper setter method 您可以使用mID默认值和适当的设置器方法进行操作

sample code: 样例代码:

class MyId{
    private String mID="";

    public void setId(final String id) {
        if(id != null) {
            mID = id;
        }
    }

    public String getId() {
        return mID;
    }
}

...
//JSON string to Object
MyId myId=new Gson().fromJson("{}", MyId.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(myId));

...
// Object to JSON string
MyId myId = new MyId();
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(myId));

output: 输出:

{
   "mID": ""
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM