Trying to serialize generic data class having with...
# serialization
d
Trying to serialize generic data class having with default value produces empty JSON object
{}
Easiest way to reproduce this issue is to try official generic classes example, add
data
modifier to the class and have default value (eg. in thread) https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#generic-classes I'm using kotlinx.serialization v1.2.2 and Kotlin v1.5.21 Update: All I had to do was read this section of doc 😅https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#encoding-defaults
Copy code
@Serializable
data class Box<T>(val contents: T)

@Serializable
data class Data(
    val a: Box<Int> = Box(42),
    val b: Box<Project> = Box(Project("kotlinx.serialization", "Kotlin"))
)

@Serializable
data class Project(val name: String, val language: String)

fun main() {
    val data = Data()
    val data2 = Data(a = Box(39))
    println(Json.encodeToString(data)) // {}
    println(Json.encodeToString(data2)) // {"a":{"contents":39}}
}
e
https://kotlinlang.slack.com/archives/C7A1U5PTM/p1630943226056800?thread_ts=1630943226.056800&amp;cid=C7A1U5PTM as announced previously, 1.3.0 will also have per-property @EncodeDefault
👌 1
658 Views