Dariusz Kuc
02/28/2021, 2:06 AMkotlinx-serialization
wraps some json elements in "
making them strings?, i.e. given generic KSerializer
object AnyKSerializer : KSerializer<Any> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Any")
...
override fun deserialize(decoder: Decoder): Any {
val jsonDecoder = decoder as JsonDecoder
val element = jsonDecoder.decodeJsonElement() // why primitives are always strings?
return deserializeJsonElement(element)
}
private fun deserializeJsonElement(element: JsonElement): Any = when (element) {
is JsonObject -> {
element.mapValues { deserializeJsonElement(it.value) }
}
is JsonArray -> {
element.map { deserializeJsonElement(it) }
}
is JsonPrimitive -> element.content
}
}
and a simple data class
@Serializable
data class AnyMap(
val data: Map<String, @Serializable(with = AnyKSerializer::class) Any>
)
trying to deserialize
{
"data": {
"intVal": 123
}
}
but jsonDecoder.decodeJsonElement()
converts 123 int to "123" string
any ideas?russhwolf
02/28/2021, 4:08 AMelement.content
it will always return a String
. You can call toInt()
or toDouble()
(or the nullable variants) to get one of those types instead, but you won’t know statically whether you can do that safely if your type is Any
.Dariusz Kuc
02/28/2021, 4:38 AMelement
is a String guess part of the confusion was the kdoc that is says it is a given element without quotes
/**
* Content of given element without quotes. For [JsonNull] this methods returns `null`
*/
public abstract val content: String
Dariusz Kuc
02/28/2021, 4:39 AMDariusz Kuc
03/01/2021, 4:51 AMelement.isString()
whether we should be converting the underlying content string or not