Hey! I became pretty enraged with ktor this week. ...
# server
m
Hey! I became pretty enraged with ktor this week. More specifically content negation with Gson. I think the mention of Gson should be removed entirely from the docs, or at the very least get a big fat warning label. Gson does not respect null safety in Kotlin. If an incoming JSON object is missing fields, Gson will not throw an error, but rather populate the field in the corresponding data class with null. Apparently is been like this for a long time, and I don’t think the gson team plans on addressing this..
😂 3
1
z
Welcome to the club 😉
j
Gson is also abandonware
Anywhere you see "Gson" read "Moshi", as it's Gson v3 in everything but name.
m
Then it definitely doesn’t belong in the ktor docs...
m
But there seems to be no official support for Moshi in Ktor 😔
d
Moshi does lack a model of Json though, which might somewhat limit usage? We also found that you couldn’t round trip top level typed lists from it (without a custom adapter) when we added moshi support to http4k (although that could be fixed by now?). TBH we just default to Jackson as it’s mostly hassle free* *there are annoyances with it for things like field naming.
j
Why would Gson throw an error if a field is missing? It is common convention to treat missing fields as null or as undefined on other platforms. Also isn't this configurable?
m
Because Kotlin doesn't allow null values unless the type is optional. @Joost Klitsie Gson will populate will nulls for non-optionals.
Copy code
data class Person(val name: String)
val person1 = Person("Jane Doe")
val person2 = Person(null) // ILLEGAL

// If GSON serializes an empty object {} you'll end up with an object like this:
// Person(name=null)
See the problem?
e
My team experienced the exact same thing.
c
@jw From what I understand/have used though... Moshi will still put null values into fields that are non-optional which seems to be @Mathias Rørvik main issue?
j
It will not
m
Gson will. It uses an unsafe method. It breaks null safety.
c
@jw is this when serializing? I know that my server sends me explicit null values for certain fields that I have defined as optional, and moshi still puts null in there.
j
i'm not sure what the problem there is. a present null and an absent value whose default is null are indistinguishable
if you have a problem please create a failing test case and submit it to the Moshi repo
c
@jw I think I stepped into server chat when I have only used moshi on the client side and so I'm probably mis-speaking. Sorry about that. I was just trying to bring up that on Android, if I have a class with no optionals, and my server sends me a null value, I will crash because moshi respects explicit nulls (which is backward to how some may think it works)
j
yep. that is working as intended! a null value doesn't fit into a non-null type. if you want to ignore that case you need to write a custom adapter to handle it.
👍 1