How do I fail json deserialization if non-nullable...
# announcements
a
How do I fail json deserialization if non-nullable fields are missing in json string?
c
Depends on your deserialization library
g
Gson or Moshi don’t provide such feature out of the box (because they are target Java, where you don’t have nullable types, all non-primitive types are nullable). You need some adapter for that. For example for Kotlin Data classes there are Moshi adapters: Kotshi (code generation of adapters) and moshi-kotlin (based on kotlin-reflect). Not sure about Gson, but I used auto-value-gson to generate AutoValue adapters with such feature, but it doesn’t work with Data classes, only with AutoValue classes
Also, as an alternative (but experimental) solution you can take a look on kotlinx.serialization #C7A1U5PTM It supports Kotlin nullability out of the box
a
Is it a standalone thing that supports working with json?
Would it be safe to use this in production?
g
standalone thing
What do you mean? Yes kotlinx.serialization supports Json out of the box. But it’s experimental and under active development.
a
I meant if it was supposed to work with other json lib like gson or has its own. Anyway. I got the answer. Thanks
g
No, it’s completely separate tool that generates bytecode directly on compile time from your annotated data class
Also it’s multiplatform and will be an official multiplatform serialization tool for Kotlin
c
@gildor @aeruhxi FYI in Klaxon, I just use default values in Kotlin to take care of that problem
g
Gson also will use default value if class has default constructor
@cedric But what will happen If I have non-null value in data class and Json doesn’t contain this value?
c
If you didn't specify a default value, Klaxon will throw an exception
g
yeah, make sense
a
Thanks, I will consider Klaxon