I'm using gson to serialize a java object to json.
Gson gson = new GsonBuilder().serializeNulls().create();
This builder handles null values that's good. But along with this I want it to handle empty string also as null.
How can this be done?
You will need to register a custom TypeAdapter that wraps the existing String TypeAdapter and replaces empty strings with JSON nulls.
Example code:
public static void main(String[] args) {
Gson gson = createGson();
System.out.println(gson.toJson(Arrays.asList("foo","bar","",null,"phleem")));
}
static Gson createGson() {
return new GsonBuilder().serializeNulls()
.registerTypeAdapter(String.class,
new EmptyToNullTypeAdapter())
.create();
}
static class EmptyToNullTypeAdapter extends TypeAdapter<String> {
@Override
public void write(final JsonWriter out, final String value) throws IOException {
if (value.isEmpty()) {
out.nullValue();
} else {
TypeAdapters.STRING.write(out, value);
}
}
@Override
public String read(final JsonReader in) throws IOException {
return TypeAdapters.STRING.read(in);
}
}
Output:
["foo","bar",null,null,"phleem"]
Caveat
Finally: not sure this is a good idea, because it's an asymmetric solution, i.e. when you deserialize an object, and then serialize it again, your new object won't be equal to the original object (nulls instead of empty strings).
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