public final TypeAdapter<T> nullSafe() {
    return new TypeAdapter<T>() {
      @Override
      public void write(JsonWriter out, T value) throws IOException {
        if (value == null) {
          out.nullValue();
        } else {
          TypeAdapter.this.write(out, value);
        }
      }

      @Override
      public T read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
          reader.nextNull();
          return null;
        }
        return TypeAdapter.this.read(reader);
      }
    };
  }
@Test
  public void testNullSafe() throws IOException {
    TypeAdapter<String> adapter =
        new TypeAdapter<String>() {
          @Override
          public void write(JsonWriter out, String value) {
            throw new AssertionError("unexpected call");
          }

          @Override
          public String read(JsonReader in) {
            throw new AssertionError("unexpected call");
          }
        }.nullSafe();

    assertThat(adapter.toJson(null)).isEqualTo("null");
    assertThat(adapter.fromJson("null")).isNull();
  }