-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnyToJsonElement.kt
42 lines (37 loc) · 1.41 KB
/
AnyToJsonElement.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package dev.yidafu.jupyper
import kotlinx.serialization.json.*
fun Any?.toJsonElement(): JsonElement = when (this) {
null -> JsonNull
is Map<*, *> -> toJsonElement()
is Collection<*> -> toJsonElement()
is ByteArray -> this.toList().toJsonElement()
is CharArray -> this.toList().toJsonElement()
is ShortArray -> this.toList().toJsonElement()
is IntArray -> this.toList().toJsonElement()
is LongArray -> this.toList().toJsonElement()
is FloatArray -> this.toList().toJsonElement()
is DoubleArray -> this.toList().toJsonElement()
is BooleanArray -> this.toList().toJsonElement()
is Array<*> -> toJsonElement()
is Boolean -> JsonPrimitive(this)
is Number -> JsonPrimitive(this)
is String -> JsonPrimitive(this)
is Enum<*> -> JsonPrimitive(this.toString())
else -> {
throw IllegalStateException("Can't serialize class, you should implement org.jetbrains.kotlinx.jupyter.api.DisplayResult interface")
}
}
fun Map<*, *>.toJsonElement(): JsonElement {
val map = mutableMapOf<String, JsonElement>()
this.forEach { (key, value) ->
// JSON object key must be String
map[key.toString()] = value.toJsonElement()
}
return JsonObject(map)
}
fun Collection<*>.toJsonElement(): JsonElement {
return JsonArray(this.map { it.toJsonElement() })
}
fun Array<*>.toJsonElement(): JsonElement {
return JsonArray(this.map { it.toJsonElement() })
}