Stylianos Gakis
10/04/2022, 11:56 AMMap<String, Any?>
and I want to turn it into JSON to then pass somewhere else.
With the type-safe builders I only see that I can do stuff like put(key:Any, value: JsonElement)
but I don’t know how to turn my Any? -> JsonElement
.
I can do stuff like
fun Any.toJsonElement() : JsonElement {
when(this) {
is Map<*, *> -> ...
is Collection<*> -> ...
}
}
and so on but I’ll most definitely do it wrong so I was looking if there’s some API I’m missing here.marstran
10/04/2022, 12:44 PMval jsonConfig = Json() // Add any configuration here if you want.
val element = jsonConfig.encodeToJsonElement(map)
Stylianos Gakis
10/04/2022, 12:46 PMSerializer for class 'Any' is not found.
Stylianos Gakis
10/04/2022, 12:50 PMinternal fun Any?.toJsonElement(): JsonElement {
return when (this) {
null -> JsonNull
is String -> JsonPrimitive(this)
is Boolean -> JsonPrimitive(this)
is Int -> JsonPrimitive(this)
is Long -> JsonPrimitive(this)
is Double -> JsonPrimitive(this)
is List<*> -> {
buildJsonArray {
for (value in this@toJsonElement) {
add(value.toJsonElement())
}
}
}
is Map<*, *> -> {
buildJsonObject {
for ((key, value) in this@toJsonElement as Map<String, *>) {
put(key, value.toJsonElement())
}
}
}
else -> error("Unsupported Any? -> JsonElement conversion for value: '$this' of type: '${this::class}'")
}
}
Heavily inspired from apollo-kotlin but I can’t help but think there must be a better way to do this when I can’t simply annotate my stuff with @Serializable
since the incoming data is unstructured.ephemient
10/04/2022, 2:19 PMAny
safely, I doubt it'll be added kotlinx.serialization.json. https://github.com/Kotlin/kotlinx.serialization/issues/296Stylianos Gakis
10/04/2022, 2:43 PMinternal fun Any?.toJsonElement(): JsonElement {
return when (this) {
null -> JsonNull
is String -> JsonPrimitive(this)
is Boolean -> JsonPrimitive(this)
is Number -> JsonPrimitive(this)
is Iterable<*> -> buildJsonArray {
for (value in this@toJsonElement) {
add(value.toJsonElement())
}
}
is Map<*, *> -> buildJsonObject {
for ((key, value) in this@toJsonElement) {
put(key.toString(), value.toJsonElement())
}
}
else -> error("Unsupported Any? -> JsonElement conversion for value: '$this' of type: '${this::class}'")
}
}
I sort of understand why it’s not there, but also have to deal with the fact that we do get some data as just “Any?” and we have to deal with it 🤷♂️Richard Gomez
10/04/2022, 7:25 PMI sort of understand why it’s not there, but also have to deal with the fact that we do get some data as just “Any?” and we have to deal with it 🤷♂️I've grumbled about this in the past. I understand why they don't do it, but I really don't think leaving people to develop their own ad-hoc subpar implementations is actually making things safer. https://kotlinlang.slack.com/archives/C7A1U5PTM/p1637210163135100?thread_ts=1637204827.132800&cid=C7A1U5PTM
Stylianos Gakis
10/04/2022, 11:41 PM