Hello here, Is there yet a way to make gson deseri...
# announcements
t
Hello here, Is there yet a way to make gson deserialization fail whenever it attempts to assign a
null
value to a kotlin non-nullable field?
https://bytes.babbel.com/en/articles/2018-05-25-kotlin-gson-nullability.html This has been an aged issue, any better solution around it?
l
afaik, no there isn't. you could try to create a custom deserializer that throws when the value is
JsonNull
but that requires creating a deserializer for every type. I'D generally recommend looking into the kotson library, it's a gson-wrapper that provides some great kotlin-idiomatic versions of gson-stuff (such as creating custom deserializers and serializers, working with generics without having to use TypeTokens (-> reified types in their functions) and so on)
a
What is the specific problem this is causing at the moment? Seems like there are easy workarounds with any given APIs that have possibility to return bad or null values
l
the main problem is that it's hard to notice. You expect null-safety in kotlin, and suddenly having null values in non-nullable fields is strange. also, for things like Int, afaik gson just stores a
0
by default. This is even harder to find and debug...
a
Are there any cases besides the following to consider? 1) API returns bad data but its still parsed as valid 200 response, like the example in the link above parsing the object "{}". 2) API can return valid object with some nullable fields
l
there is also "programmer did a typo on an int variable, and is now searching for the cause of everything being
0
for multiple hours before looking into the gotchas of gson" and "API had a breaking change that renamed a field, thus now the client-side deserialization fails silently and will be unnoticed for some time"
a
Gson alternative then?
d
Is there a reason not to switch to Jackson is Gson just doesn't work?
t
Thanks @Leon K I’d take a look at kotson
@Andrew the api I am dealing with has a lot of inconsistencies so I must be able to handle things while deserializing
a
I've seen Moshi mentioned as well too (the only one I've used actually). There are some less than ideal solutions for gson and it seems like alternative with better kotlin support is the best option.
👍 1