Replace null with empty string on serialization

6403 views
Skip to first unread message

abp

unread,
Dec 2, 2010, 7:36:48 AM12/2/10
to google-gson
Hi,

is it possible to write an empty string instead of null to the json,
when it encounters nulls in my pojos?

Angel Aguilera

unread,
Dec 9, 2010, 5:00:46 AM12/9/10
to google-gson
On Dec 2, 1:36 pm, abp <adr...@needful.de> wrote:
> is it possible to write an empty string instead of null to the json,
> when it encounters nulls in my pojos?

My bet would be to define a custom converter for the String class.
Something like this:

public class StringConverter implements JsonSerializer<String>,
JsonDeserializer<String> {
public JsonElement serialize(String src, Type typeOfSrc,
JsonSerializationContext context) {
if ( src == null ) {
return new JsonPrimitive("");
} else {
return new JsonPrimitive(src.toString());
}

public String deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return json.getAsJsonPrimitive().getAsString();
}
}


After that, in the class you want to serialize, you must register the
converter in your gson object:

GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(String.class, new StringConverter());
Gson gson = gb.create();

Then you can use the "gson" object to serialize your objects.

abp

unread,
Dec 10, 2010, 10:01:13 AM12/10/10
to google-gson
Hm yeah, but i meant nulls of all types.

Hanuman G

unread,
Dec 13, 2013, 12:26:47 PM12/13/13
to googl...@googlegroups.com, angel.a...@gmail.com
This didn't work for me, so i ended up doing like this   using Gson gson = new GsonBuilder().serializeNulls().create();
        String json = gson.toJson(obj5); json = json.replaceall("null","\"\"");  may  be it will be slow  if  u have  very  large string with null values . not sure about performance. Its disappointing  API  is unable  to  support   as in the below code.
Reply all
Reply to author
Forward
0 new messages