Quantcast
Channel: Gson Serialize field only if not null or not empty - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Gson Serialize field only if not null or not empty

$
0
0

I have requirement where I need to convert java object to json.

I am using Gson for that but i need the converter to only serialize the non null or not empty values.

For example:

//my java object looks likeclass TestObject{    String test1;    String test2;    OtherObject otherObject = new OtherObject();}

now my Gson instance to convert this object to json looks like

Gson gson = new Gson();TestObject obj = new TestObject();obj.test1 = "test1";obj.test2 = "";String jsonStr = gson.toJson(obj);println jsonStr;

In the above print, the result is

{"test1":"test1", "test2":"", "otherObject":{}}

Here i just wanted the result to be

{"test1":"test1"}

Since the test2 is empty and otherObject is empty, i don't want them to be serialized to json data.

Btw, I am using Groovy/Grails so if there is any plugin for this that would be good, if not any suggestion to customize the gson serialization class would be good.


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>