Allow working with JSON5 without @Serializable
classes #2
Description
I would like to be able to encode or decode JSON5 without using @Serializable
classes.
Context
This is useful for tweaking JSON5 elements during serialization (for example, in a custom KSerializer
), or for use in contexts where the Kotlinx Serialization plugin isn't available (Gradle config, .main.kts scripts)
KxS JsonElement
Kotlinx Serialization already provides JsonElement
for this purpose.
Aside from direct conversions between strings and JSON objects, Kotlin serialization offers APIs that allow other ways of working with JSON in the code. For example, you might need to tweak the data before it can parse or otherwise work with such an unstructured data that it does not readily fit into the typesafe world of Kotlin serialization.
https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#json-elements
JsonElement
example
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
fun main() {
val jsonObj: JsonObject = Json.decodeFromString("""
{
"some": "json",
"count": 123
}
""".trimIndent())
println(jsonObj)
}
Options
I think there are two options
- json5k re-implements the
JsonElement
code, but for JSON5. This is mostly an exercise in renaming! - json5k re-uses the existing
JsonElement
code. Since JSON and JSON5 are so similar, I suspect this is the easiest approach.