mirror of
https://github.com/InsanusMokrassar/TelegramBotAPI.git
synced 2024-06-01 23:45:25 +00:00
48 lines
1.4 KiB
Kotlin
48 lines
1.4 KiB
Kotlin
|
package com.github.insanusmokrassar.TelegramBotAPI.utils
|
||
|
|
||
|
import kotlinx.serialization.*
|
||
|
import kotlinx.serialization.json.*
|
||
|
|
||
|
@ImplicitReflectionSerializer
|
||
|
inline fun <reified T: Any> T.toJsonWithoutNulls(): JsonObject = toJson(serializerByValue(this)).withoutNulls()
|
||
|
|
||
|
inline fun <reified T: Any> T.toJsonWithoutNulls(serializer: KSerializer<T>): JsonObject = toJson(serializer).withoutNulls()
|
||
|
|
||
|
inline fun <reified T: Any> T.toJson(serializer: KSerializer<T>): JsonObject = JsonTreeMapper().writeTree(
|
||
|
this,
|
||
|
serializer
|
||
|
).jsonObject
|
||
|
|
||
|
fun JsonArray.withoutNulls(): JsonArray {
|
||
|
return jsonArray {
|
||
|
forEach {
|
||
|
when (it) {
|
||
|
is JsonObject -> +it.withoutNulls()
|
||
|
is JsonArray -> +it.withoutNulls()
|
||
|
is JsonPrimitive -> +it
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fun JsonObject.withoutNulls(): JsonObject {
|
||
|
return json {
|
||
|
forEach { (k, v) ->
|
||
|
when (v) {
|
||
|
is JsonObject -> k to v.withoutNulls()
|
||
|
is JsonArray -> k to v.withoutNulls()
|
||
|
!is JsonNull -> k to v
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fun JsonObject.mapWithCommonValues(): Map<String, Any> = map {
|
||
|
(key, value) ->
|
||
|
key to when (value) {
|
||
|
is JsonPrimitive -> value.contentOrNull ?: value.booleanOrNull ?: value.doubleOrNull ?: value.floatOrNull ?: value.intOrNull
|
||
|
is JsonArray, is JsonObject -> value.toString()
|
||
|
is JsonNull -> null
|
||
|
}
|
||
|
}.toMap().mapNotNullValues()
|