Gson: Gson skip call of specified TypeAdapter if value is null

Created on 26 Oct 2016  路  3Comments  路  Source: google/gson

reproduced on 2.7 version

Here is some test.

 public static class A {
        @JsonAdapter(NullTolerantStringAdapter.class)
        String nonNullString = "";

        public static class NullTolerantStringAdapter extends TypeAdapter<String> {

            @Override
            public void write(JsonWriter out, String value) throws IOException {
                out.value(value);
            }

            @Override
            public String read(JsonReader in) throws IOException {
                String val = in.nextString();
                return val != null ? val : "";
            }
        }
    }

    @Test
    public void testNullDeserialization () {
        A a = new A();
        a.nonNullString = null;

        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(a);
        A deserialized = gson.fromJson(json, A.class);

        assertThat(deserialized.nonNullString).isNotNull();

        Gson gsonWithNull = new GsonBuilder().serializeNulls().create();
        String jsonWithNull = gson.toJson(a);
        A deserializedWithNull = gsonWithNull.fromJson(jsonWithNull, A.class);

        assertThat(deserializedWithNull.nonNullString).isNotNull();
    }

First assert is passed (with no value for field custom read method is also not called but ok)

Second assert is not passed because custom read never called.

So I can't see how to guarantee non nullability for field without custom TypeAdapter for the whole class.

Most helpful comment

This is the default behavior of Gson. Null values don't invoke type adapters.

Seriously? Null values do not invoke type adapters. Null values do not invoke custom deserializers... Does it mean it's impossible to override null deserialization in Gson?

Sucks if it's true.

All 3 comments

This is the default behavior of Gson. Null values don't invoke type adapters.

This is the default behavior of Gson. Null values don't invoke type adapters.

Seriously? Null values do not invoke type adapters. Null values do not invoke custom deserializers... Does it mean it's impossible to override null deserialization in Gson?

Sucks if it's true.

If this is the default behavior, then is there a way to override it?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cayhorstmann picture cayhorstmann  路  13Comments

GoogleCodeExporter picture GoogleCodeExporter  路  25Comments

GoogleCodeExporter picture GoogleCodeExporter  路  15Comments

GoogleCodeExporter picture GoogleCodeExporter  路  32Comments

GoogleCodeExporter picture GoogleCodeExporter  路  15Comments