Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization omitting nulls

I have a class like this:

@Serializable
data class MyClass(
    val prop1: Int,
    val prop2: Int?
)

When prop2 is null, I want to serialize this class without including the prop2 property. I can do this like this:

val json = Json { explicitNulls = false }
json.encodeToString(MyClass(42, null))  // gives {"prop1": 42}

Unfortunately, there are many places in a large project that serialize this class, and currently they just use Json.encodeToString which includes the nulls explicitly.

How can I enforce the serialization of this class to not serialize nulls? I need this to apply just to this class; other serializable classes in the project need to continue to have explicit nulls.

like image 502
k314159 Avatar asked Sep 11 '25 08:09

k314159


1 Answers

If you can give the selected fields a default of null, then you can use the EncodeDefault annotation:

@Serializable
data class MyClass(
    val prop1: Int,
    @EncodeDefault(NEVER) val prop2: Int? = null
)

This will avoid encoding prop2 if it is null, irrespective of the setting of the encodeDefaults property of the Json serializer you use when you serialize your class instance.

like image 197
Klitos Kyriacou Avatar answered Sep 14 '25 00:09

Klitos Kyriacou