Gson serialize null for specific class or field

后端 未结 5 446
面向向阳花
面向向阳花 2021-01-01 11:00

I want to serialize nulls for a specific field or class.

In GSON, the option serializeNulls() applies to the whole JSON.

Example:



        
5条回答
  •  暖寄归人
    2021-01-01 11:57

    I have interface to check when object should be serialized as null:

    public interface JsonNullable {
      boolean isJsonNull();
    }
    

    And the corresponding TypeAdapter (supports write only)

    public class JsonNullableAdapter extends TypeAdapter {
    
      final TypeAdapter elementAdapter = new Gson().getAdapter(JsonElement.class);
      final TypeAdapter objectAdapter = new Gson().getAdapter(Object.class);
    
      @Override
      public void write(JsonWriter out, JsonNullable value) throws IOException {
        if (value == null || value.isJsonNull()) {
          //if the writer was not allowed to write null values
          //do it only for this field
          if (!out.getSerializeNulls()) {
            out.setSerializeNulls(true);
            out.nullValue();
            out.setSerializeNulls(false);
          } else {
            out.nullValue();
          }
        } else {
          JsonElement tree = objectAdapter.toJsonTree(value);
          elementAdapter.write(out, tree);
        }
      }
    
      @Override
      public JsonNullable read(JsonReader in) throws IOException {
        return null;
      }
    }
    
    
    

    Use it as follows:

    public class Foo implements JsonNullable {
      @Override
      public boolean isJsonNull() {
        // You decide
      }
    }
    

    In the class where Foo value should be serialized as null. Note that foo value itself must be not null, otherwise custom adapter annotation will be ignored.

    public class Bar {
      @JsonAdapter(JsonNullableAdapter.class)
      public Foo foo = new Foo();
    }
    

    提交回复
    热议问题