Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2/ Gson null values are not skipped when DEFAULT_SERIALIZE_NULLS value is used

I am running into some unknown error. This breaks my assumption of null-safety with Kotlin data class and Api responses.

Say, I have a data class say Person:

 data class Person(val name: String) {
    constructor() : this("")
}

This will generate an object Person with default name value i.e. non-null. Earlier, When I use a default retrofit client with GsonConverterFactory.create() (added as a converter factory). In default mode, Gson doesn't serialize a null value. But today I found out that field is getting serialized to null.

I verfiy the same in ReflectiveTypeAdapterFactory https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java#L206

Here the instance value is having non-null field but after reading each field (field.read(in, instance);) it is assigning the null value. I am expecting the null values to be skipped during serialization or is it deserialization?


Edit: Looks like it is deserializing nulls not serializing null problem. Reference: https://github.com/google/gson/issues/1148

Let me know if any detail missing or creating confusion.

like image 955
Shubham Agarwal Avatar asked Jan 28 '20 13:01

Shubham Agarwal


1 Answers

You have to make name parameter nullable by changing type;

String

to

String?
like image 147
Masoud Darzi Avatar answered Nov 10 '22 05:11

Masoud Darzi