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.