Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON without data class in Kotlin?

Tags:

json

kotlin

There are many JSON parsers in Kotlin like Forge, Gson, JSON, Jackson... But they deserialize the JSON to a data class, meaning it's needed to define a data class with the properties corresponding to the JSON, and this for every JSON which has a different structure.

But what if you don't want to define a data class for every JSON you could have to parse?

I'd like to have a parser which wouldn't use data classes, for example it could be something like:

val jsonstring = '{"a": "b", "c": {"d: "e"}}'

parse(jsonstring).get("c").get("d") // -> "e"

Just something that doesn't require me to write a data class like

data class DataClass (
    val a: String,
    val b: AnotherDataClass
)

data class AnotherDataClass (
    val d: String
)

which is very heavy and not useful for my use case.

Does such a library exist? Thanks!

like image 868
Kureteiyu Avatar asked Mar 14 '26 10:03

Kureteiyu


2 Answers

With kotlinx.serialization you can parse JSON String into a JsonElement:

val json: Map<String, JsonElement> = Json.parseToJsonElement(jsonstring).jsonObject
like image 200
Михаил Нафталь Avatar answered Mar 15 '26 22:03

Михаил Нафталь


You can use JsonPath

val json = """{"a": "b", "c": {"d": "e"}}"""
val context = JsonPath.parse(json)
val str = context.read<String>("c.d")
println(str)

Output:

Result: e

like image 28
Nikolai Shevchenko Avatar answered Mar 15 '26 22:03

Nikolai Shevchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!