I'm using Gson with Retrofit, and I have a case where I need to serialize a single null field, but I cannot turn on the global serializeNulls() flag for Gson, because it will break the rest of my code. Does anyone know how to accomplish this?
Here's what I've tried:
I also couldn't figure out a way to add to the serialized json, since it all happens inside Retrofit.
I solved this problem by setting setSerializeNulls(true) and restoring original value to JsonWriter in TypeAdapter.write():
public class NullableDoubleAdapter extends TypeAdapter<NullableDouble> {
@Override
public void write(final JsonWriter out, final NullableDouble value) throws IOException {
if (value == null) {
boolean serializeNulls = out.getSerializeNulls();
out.setSerializeNulls(true);
out.nullValue();
out.setSerializeNulls(serializeNulls);
} else {
out.value(value.getValue());
}
}
...
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