Thanabodee Charoenpiriyakij
05/31/2022, 11:10 AMRob Elliot
05/31/2022, 11:16 AMMap<String, Object>
into a data class without turning it into JSON as an intermediate: https://stackoverflow.com/questions/16428817/convert-a-mapstring-string-to-a-pojoThanabodee Charoenpiriyakij
05/31/2022, 11:24 AMephemient
05/31/2022, 11:31 AMephemient
05/31/2022, 11:32 AMJsonObject
and Map<String, Object>
James Richardson
05/31/2022, 12:21 PMThanabodee Charoenpiriyakij
05/31/2022, 12:58 PMThanabodee Charoenpiriyakij
05/31/2022, 12:59 PMJames Richardson
05/31/2022, 1:04 PMephemient
06/01/2022, 3:39 AMJsonElement
and "`Object` that is primitive or string or list or map" is pretty straightforward,
fun JsonElement.toObject(): Any? = when (this) {
is JsonPrimitive -> booleanOrNull ?: intOrNull ?: longOrNull ?: doubleOrNull ?: contentOrNull
is JsonArray -> map { it.toObject() }
is JsonObject -> mapValues { it.value.toObject() }
}
@Suppress("UNCHECKED_CAST")
fun Any?.toJson(): JsonElement = when (this) {
null -> JsonNull
is Boolean -> JsonPrimitive(this)
is Number -> JsonPrimitive(this)
is String -> JsonPrimitive(this)
is Iterable<*> -> buildJsonArray {
forEach { add(it.toJson()) }
}
is Map<*, *> -> buildJsonObject {
forEach { put(it.key as String, it.value.toJson()) }
}
else -> throw IllegalArgumentException()
}