Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlinx Serialization - Custom serializer to ignore null value

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.

like image 560
H.Nguyen Avatar asked Sep 23 '19 06:09

H.Nguyen


2 Answers

Use encodeDefaults = false property in JsonConfiguration and it won't serialize nulls (or other optional values)

like image 171
kissed Avatar answered Nov 12 '22 16:11

kissed


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

like image 4
saymyname Avatar answered Nov 12 '22 14:11

saymyname