Skip to content

Commit

Permalink
fix: rescope json
Browse files Browse the repository at this point in the history
  • Loading branch information
bgiori committed Feb 29, 2024
1 parent a99948d commit f889c2f
Showing 1 changed file with 22 additions and 22 deletions.
44 changes: 22 additions & 22 deletions core/src/main/kotlin/util/Json.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,7 @@ val json = Json {
explicitNulls = false
}

object AnySerializer : KSerializer<Any?> {
private val delegate = JsonElement.serializer()
override val descriptor: SerialDescriptor
get() = SerialDescriptor("Any", delegate.descriptor)

override fun serialize(encoder: Encoder, value: Any?) {
val jsonElement = value.toJsonElement()
encoder.encodeSerializableValue(delegate, jsonElement)
}

override fun deserialize(decoder: Decoder): Any? {
val jsonElement = decoder.decodeSerializableValue(delegate)
return jsonElement.toAny()
}
}

fun Any?.toJsonElement(): JsonElement = when (this) {
internal fun Any?.toJsonElement(): JsonElement = when (this) {
null -> JsonNull
is Map<*, *> -> toJsonObject()
is Collection<*> -> toJsonArray()
Expand All @@ -49,30 +33,46 @@ fun Any?.toJsonElement(): JsonElement = when (this) {
else -> JsonPrimitive(toString())
}

fun Collection<*>.toJsonArray(): JsonArray = JsonArray(map { it.toJsonElement() })
internal fun Collection<*>.toJsonArray(): JsonArray = JsonArray(map { it.toJsonElement() })

fun Map<*, *>.toJsonObject(): JsonObject = JsonObject(
internal fun Map<*, *>.toJsonObject(): JsonObject = JsonObject(
mapNotNull {
(it.key as? String ?: return@mapNotNull null) to it.value.toJsonElement()
}.toMap()
)

fun JsonElement.toAny(): Any? {
internal fun JsonElement.toAny(): Any? {
return when (this) {
is JsonPrimitive -> toAny()
is JsonArray -> toList()
is JsonObject -> toMap()
}
}

fun JsonPrimitive.toAny(): Any? {
internal fun JsonPrimitive.toAny(): Any? {
return if (isString) {
contentOrNull
} else {
booleanOrNull ?: intOrNull ?: longOrNull ?: doubleOrNull
}
}

fun JsonArray.toList(): List<Any?> = map { it.toAny() }
internal fun JsonArray.toList(): List<Any?> = map { it.toAny() }

fun JsonObject.toMap(): Map<String, Any?> = mapValues { it.value.toAny() }

internal object AnySerializer : KSerializer<Any?> {
private val delegate = JsonElement.serializer()
override val descriptor: SerialDescriptor
get() = SerialDescriptor("Any", delegate.descriptor)

override fun serialize(encoder: Encoder, value: Any?) {
val jsonElement = value.toJsonElement()
encoder.encodeSerializableValue(delegate, jsonElement)
}

override fun deserialize(decoder: Decoder): Any? {
val jsonElement = decoder.decodeSerializableValue(delegate)
return jsonElement.toAny()
}
}

0 comments on commit f889c2f

Please sign in to comment.