Johann
Johann

Reputation: 29877

Exclude non-null properties when serializing a Kotlin data class

I often will create a data class in Kotlin that is used internally for data models. Example:

data class MyDataModel(
    var id: String? = null,
    var ownerId: String,
    var name: String,
    var isPrivate: Boolean = false,
)

I often need to serialize these classes to JSON. The problem is that some of the class properties are not nullable and there are cases where I need to exclude those fields in the serialization. I haven't found a clean and simple way to do that. The solution I currently use is not to use non-nullable properties and then set those that I don't want serialized to null.

Is there another approach?

Upvotes: 0

Views: 3254

Answers (1)

Solution using kotlinx.serialization:

  1. Define class, including all fields you want to be serialized, mark it as @Serializable
@Serializable
open class MyDataModelSerializable(
    open var id: String? = null
)
  1. Make your data class to be its subtype:
data class MyDataModel(
    var ownerId: String,
    var name: String,
    var isPrivate: Boolean = false,
    override var id: String? = null
) : MyDataModelSerializable(id)
  1. Serialize instances of MyDataModel class with serializer for MyDataModelSerializable:
val s = serializer<MyDataModelSerializable>()
println(Json.encodeToString(s, MyDataModel(ownerId = "1", name = "2", id = "3", isPrivate = true))) //{"id":"3"}
println(Json.encodeToString(s, MyDataModel(ownerId = "1", name = "2", isPrivate = true))) //{}
println(Json{encodeDefaults = true}.encodeToString(s, MyDataModel(ownerId = "1", name = "2"))) //{"id":null}

Upvotes: 0

Related Questions