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.
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?
Most helpful comment
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.