Hong
09/05/2018, 4:51 PMdata class Person(val name: String, val age: Int, val desc: String = "")
When cloud JSON (via Retrofit and Gson) comes back w/ null value for desc
field, the resultant Person
instance will have null value for desc
field, instead of empty string. So the non-null field desc
can have null value.
I searched online for some solutions but they all seem hacky, anyone has any good suggestion?maxmello
09/05/2018, 8:21 PMHong
09/05/2018, 8:22 PMgildor
09/06/2018, 2:23 AMuses Java’s reflection to set the valuesMoshi and Jackson, everyone use Java reflections by default. moshi-kotlin also uses reflections, but Kotlin reflections, but also provides an option to generate adapters using kapt
Hong
09/06/2018, 2:26 AMgildor
09/06/2018, 2:27 AMdata class Person(val name: String = "", val age: Int = -1, val desc: String = "")
Kotlin will generate default constuctor and Gson will use this constructor instead of sun.misc.Unsafe to create an instance of the object and then set values from Json using reflection"desc": null
, Gson will overwrite your default empty string with null and your program will crash on access to this propertyHong
09/06/2018, 2:33 AMdesc
can have null value, which will lead to runtime NPE.gildor
09/06/2018, 2:34 AMHong
09/06/2018, 2:34 AMgildor
09/06/2018, 2:35 AMval desc: String? = ""
Hong
09/06/2018, 2:35 AMmaxmello
09/06/2018, 6:55 AMMoshi just has additional library adapter for KotlinYeah sorry thats what I meant even though its not what I wrote… I didn’t actually know that the default values work when every property has a default, but the part about passing in null is pretty risk in my opinion, unless you are in full control of the API you call and can make sure nulls are never included in a JSON.
gildor
09/06/2018, 7:44 AMmake sure nulls are never included in a JSONYes, if you not sure about API you always can use nullable values, Kotlin provides a lot of tools for that
zone
09/10/2018, 1:38 PMgildor
09/10/2018, 2:03 PM