Created
June 16, 2024 09:19
-
-
Save andhikayuana/bba9099e8fd0b939074c3c0a670d1e07 to your computer and use it in GitHub Desktop.
Kotlinx Json Extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.serialization.json.JsonArray | |
import kotlinx.serialization.json.JsonElement | |
import kotlinx.serialization.json.JsonNull | |
import kotlinx.serialization.json.JsonObject | |
import kotlinx.serialization.json.JsonPrimitive | |
fun Any?.toJsonElement(): JsonElement { | |
return when (this) { | |
is Number -> JsonPrimitive(this) | |
is Boolean -> JsonPrimitive(this) | |
is String -> JsonPrimitive(this) | |
is Array<*> -> this.toJsonArray() | |
is List<*> -> this.toJsonArray() | |
is Map<*, *> -> this.toJsonObject() | |
is JsonElement -> this | |
else -> JsonNull | |
} | |
} | |
fun Array<*>.toJsonArray(): JsonArray { | |
val array = mutableListOf<JsonElement>() | |
this.forEach { array.add(it.toJsonElement()) } | |
return JsonArray(array) | |
} | |
fun List<*>.toJsonArray(): JsonArray { | |
val array = mutableListOf<JsonElement>() | |
this.forEach { array.add(it.toJsonElement()) } | |
return JsonArray(array) | |
} | |
fun Map<*, *>.toJsonObject(): JsonObject { | |
val map = mutableMapOf<String, JsonElement>() | |
this.forEach { | |
if (it.key is String) { | |
map[it.key as String] = it.value.toJsonElement() | |
} | |
} | |
return JsonObject(map) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment