Let's say I'm having a class like:
@Serializable
data class MyClass(
@SerialName("a") val a: String?,
@SerialName("b") val b: String
)
Assume the a
is null
and b
's value is "b value", then Json.stringify(MyClass.serializer(), this)
produces:
{ "a": null, "b": "b value" }
Basically if a
is null
, I wanted to get this:
{ "b": "b value" }
From some research I found this is currently not doable out of the box with Kotlinx Serialization so I was trying to build a custom serializer to explicitly ignore null
value. I followed the guide from here but couldn't make a correct one.
Can someone please shed my some light? Thanks.
Use encodeDefaults = false
property in JsonConfiguration
and it won't serialize nulls (or other optional values)
You can use explicitNulls = false
example:
@OptIn(ExperimentalSerializationApi::class)
val format = Json { explicitNulls = false }
@Serializable
data class Project(
val name: String,
val language: String,
val version: String? = "1.3.0",
val website: String?,
)
fun main() {
val data = Project("kotlinx.serialization", "Kotlin", null, null)
val json = format.encodeToString(data)
println(json) // {"name":"kotlinx.serialization","language":"Kotlin"}
}
https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#explicit-nulls
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