All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.github.insanusmokrassar.TelegramBotAPI.utils.JSON.kt Maven / Gradle / Ivy

There is a newer version: 0.28.3
Show newest version
package com.github.insanusmokrassar.TelegramBotAPI.utils

import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.json.*

internal val nonstrictJsonFormat = Json {
    isLenient = true
    ignoreUnknownKeys = true
    serializeSpecialFloatingPointValues = true
    useArrayPolymorphism = true
}

fun  T.toJsonWithoutNulls(serializer: SerializationStrategy): JsonObject = toJson(serializer).withoutNulls()

fun  T.toJson(serializer: SerializationStrategy): JsonObject = nonstrictJsonFormat.toJson(
    serializer,
    this
).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 = 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()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy