Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON: Serialize a single null field without using the global serializeNulls()

Tags:

json

android

gson

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:

  • Make an annotation, @SerializeNull. This would be the ideal solution, but it failed because the serializeNulls flag is actually on the JsonWriter, which is downstream of the ExclusionStrategy.
  • Use a TypeAdapterFactory. Again, the JsonWriter is downstream.

I also couldn't figure out a way to add to the serialized json, since it all happens inside Retrofit.

like image 657
GLee Avatar asked Jan 26 '16 02:01

GLee


1 Answers

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());
    }
  }
...
like image 84
Andriy Petruk Avatar answered Oct 21 '22 02:10

Andriy Petruk