Joel Steres
04/18/2022, 11:56 PM@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.ephemient
04/19/2022, 2:13 AMephemient
04/19/2022, 2:17 AMephemient
04/19/2022, 2:34 AM@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})")
}
⇒
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)
Joel Steres
04/19/2022, 8:05 AM