Skip to content

Gson skip call of specified TypeAdapter if value is null #948

@StanisVS

Description

@StanisVS

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions