I use google-gson to serialize a Java map into a JSON string. It provides a builder handles null values:
Gson gson = new GsonBuilder().serializeNulls().create();
The problem is that the result is the string null
, as in:
gson.toJson(categoriesMap)); {"111111111":null}
And the required result is:
{"111111111":""}
I can do a String-replace for null
and ""
, but this is ugly and prone to errors. Is there a native gson support for adding a custom String instead of null
?
The above answer works okay for serialisation, but on deserialisation, if there is a field with null value, Gson will skip it and won't enter the deserialize method of the type adapter, therefore you need to register a TypeAdapterFactory and return type adapter in it.
Gson gson = GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create(); public static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>) type.getRawType(); if (rawType != String.class) { return null; } return (TypeAdapter<T>) new StringAdapter(); } } public static class StringAdapter extends TypeAdapter<String> { public String read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return ""; } return reader.nextString(); } public void write(JsonWriter writer, String value) throws IOException { if (value == null) { writer.nullValue(); return; } writer.value(value); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With