I declared a data class
like this:
data class Product(val name: String = "", val price: Float = 0f)
My code is:
val json = "{'name': null, 'price': 50.00}"
val gson = GsonBuilder().create()
val p = gson.fromJson(json, Product::class.java)
println("name is ${p.name}")
The console output is: name is null
How is this possible? The name attribute is not a nullable string.
That's common problem when using Gson with Kotlin - and the runtime errors occur far too late here, which may make your program unstable and crash-friendly. For example, write:
val name: String = p.name
Boom! Crash.
Gson simply, as per super hacky implementation, allocates memory for the class without calling the constructor, and later fills fields with values that are present in JSON using reflection.
This makes it possible to store null
in Kotlin's not-null properties, and that can cause NPE at runtime. You can provide custom TypeAdapter to disable reflection for your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With