Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions commons-jvm/src/main/java/org/mtransit/commons/JsonExt.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package org.mtransit.commons

import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.double
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.long
import kotlinx.serialization.json.longOrNull

fun Any?.toJsonElement(): JsonElement = when (this) {
null -> JsonNull
is JsonElement -> this
is Number -> JsonPrimitive(this)
is Boolean -> JsonPrimitive(this)
is String -> JsonPrimitive(this)
is Enum<*> -> JsonPrimitive(this.name)
is Map<*, *> -> JsonObject(
this.entries.associate { (k, v) -> k.toString() to v.toJsonElement() }
)

is Iterable<*> -> JsonArray(this.map { it.toJsonElement() })
is Array<*> -> JsonArray(this.map { it.toJsonElement() })
else -> throw IllegalArgumentException("Unsupported type for JsonElement: ${this::class}")
Comment on lines +28 to +30

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In Kotlin, primitive arrays (such as IntArray, LongArray, DoubleArray, etc.) do not inherit from Array<*>. As a result, passing any primitive array to toJsonElement() will fall through to the else branch and throw an IllegalArgumentException at runtime.

To make this function robust and support all array types, we should explicitly handle primitive arrays in the when expression.

Suggested change
is Iterable<*> -> JsonArray(this.map { it.toJsonElement() })
is Array<*> -> JsonArray(this.map { it.toJsonElement() })
else -> throw IllegalArgumentException("Unsupported type for JsonElement: ${this::class}")
is Iterable<*> -> JsonArray(this.map { it.toJsonElement() })
is Array<*> -> JsonArray(this.map { it.toJsonElement() })
is ByteArray -> JsonArray(this.map { it.toJsonElement() })
is ShortArray -> JsonArray(this.map { it.toJsonElement() })
is IntArray -> JsonArray(this.map { it.toJsonElement() })
is LongArray -> JsonArray(this.map { it.toJsonElement() })
is FloatArray -> JsonArray(this.map { it.toJsonElement() })
is DoubleArray -> JsonArray(this.map { it.toJsonElement() })
is BooleanArray -> JsonArray(this.map { it.toJsonElement() })
is CharArray -> JsonArray(this.map { it.toJsonElement() })
else -> throw IllegalArgumentException("Unsupported type for JsonElement: ${this::class}")

}

fun Any?.toJsonPrimitive(): JsonPrimitive = when (this) {
null -> JsonNull
is JsonPrimitive -> this
is Number -> JsonPrimitive(this)
is Boolean -> JsonPrimitive(this)
is String -> JsonPrimitive(this)
is Enum<*> -> JsonPrimitive(this.name)
else -> throw IllegalArgumentException("Cannot convert ${this::class} to JsonPrimitive")
}

val JsonElement.jsonPrimitiveOrNull get() = this as? JsonPrimitive
val JsonElement.jsonObjectOrNull get() = this as? JsonObject
val JsonElement.jsonArrayOrNull get() = this as? JsonArray
val JsonElement.jsonNullOrNull get() = this as? JsonNull

fun JsonElement.toAny(): Any? = when (this) {
is JsonNull -> null
is JsonPrimitive -> when {
isString -> content
booleanOrNull != null -> boolean
longOrNull != null -> long
doubleOrNull != null -> double
else -> content
}
Comment on lines +50 to +56

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In the current implementation, standard library functions like booleanOrNull, longOrNull, and doubleOrNull are called to check if the value matches a type, and then the corresponding throwing properties (boolean, long, double) are called again to retrieve the value. This results in parsing the string representation twice for each type check.

We can optimize this by using the Elvis operator (?:) to retrieve and return the parsed value directly, avoiding redundant parsing.

    is JsonPrimitive -> if (isString) {
        content
    } else {
        booleanOrNull ?: longOrNull ?: doubleOrNull ?: content
    }

is JsonObject -> mapValues { it.value.toAny() }
is JsonArray -> map { it.toAny() }
}

inline fun JsonObject.edit(builderAction: JsonObjectBuilder.() -> Unit): JsonObject {
return buildJsonObject {
forEach { (key, value) -> put(key, value) }
builderAction()
}
}