Hi. I am trying to merge a serialized data class ...
# serialization
j
Hi. I am trying to merge a serialized data class into a json object which may have values not included in the data class. I am doing something similar to this.
Copy code
@Serializable
data class Xxx(...) {
    fun merge(apiSnapshot: String): JSONObject {
        val merged = JSONObject(apiSnapshot)
        Json.encodeToJsonElement(this).jsonObject.entries.forEach { (key, value) ->
            if (value == null) {
                merged.remove(key)
            } else {
                merged.put(key, value)
            }
        }
        return merged
    }
}
However, the values are from the serialized
JsonObject
are all strings, including nulls. Is there a way to do this that preserves the type? I also tried
encodeToString
and parsing with
JSONObject
, which does preserve the types, but I lost nulls when I did this. I could combine the two approaches but I’m hoping there is a more elegant approach.
e
it's not that hard to write your own basic Format which produces JSONObject/JSONArray/String/primitive directly without going through JsonElement, but it will miss out on standard Json features like JsonClassDiscriminator, JsonTransformingSerializer, etc.
with the above,
Copy code
@Serializable
data class Foo(val z: Boolean, val b: Byte, val s: Short, val c: Char, val i: Int, val l: Long, val f: Float, val g: Double)
val jsonObject = JSONFormat().encode(Foo(false, 1, 2, '3', 4, 5, 6.7f, 8.9)) as JSONObject
val names = jsonObject.names()
for (i in 0 until (names?.length() ?: 0)) {
    val key = names.get(i) as String
    val value = jsonObject.get(key)
    println("$key => $value (${value.javaClass})")
}
Copy code
z => false (class java.lang.Boolean)
b => 1 (class java.lang.Byte)
s => 2 (class java.lang.Short)
c => 3 (class java.lang.Character)
i => 4 (class java.lang.Integer)
l => 5 (class java.lang.Long)
f => 6.7 (class java.lang.Float)
g => 8.9 (class java.lang.Double)
j
@ephemient thank you! Seeing this really helps me understand how this fits together better and direct me to useful parts of the documentation. Much appreciated.
160 Views