I'm sorta new to kotlinx.serailization. Here's so...
# serialization
c
I'm sorta new to kotlinx.serailization. Here's something that blew up at runtime that surprised me:
Copy code
@Serializable
data class MyResponseBody(
    val id: Long,
    val email: String,
    val username: String?
)
I got an error of
Field 'username' is required for type with serial name
Why is that. Doesn't the
?
indicate that it's not required? If not, then how can I catch this at compile time? Seems like marking something with @Serializable should enforce that any
?
field should have a default, no?
j
The question mark makes the type nullable, meaning it is still required but accepts null
What you're asking for is behavior that supports absence which are not the same
That is what a default expression provides (and is useful regardless of nullability)
Consider
{"presentNotNull":"present","presentNull":null}
and the three properties that would bind to it: presentNotNull, presentNull, and absent
presentNotNull can be of type String or String? and if it has a default expression it won't be used
presentNull can only be String? but not String and the default expression will not be used
absent can be of type String or String? and the default expression will be used
s
You should be able to set a default value, which would be used if the field was not present in the serialized data.
Copy code
@Serializable
data class MyResponseBody(
  val id: Long,
  val email: String,
  val username: String? = null,
)
Alternatively, at least if you're using kotlinx.serialization.json, you can configure
Json
to not require explicit nulls by setting
explicitNulls = false
. https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-builder/explicit-nulls.html
c
Makes sense. Thank you both!
👍 1
👍🏾 1