Kureteiyu
Kureteiyu

Reputation: 639

Parse JSON without data class in 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!

Upvotes: 12

Views: 12549

Answers (2)

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

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

Upvotes: 2

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

val json: Map<String, JsonElement> = Json.parseToJsonElement(jsonstring).jsonObject

Upvotes: 10

Related Questions