12

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!

4
  • Please check this answer. I believe it applies to your use case. Commented Jan 30, 2022 at 21:42
  • I guess you're refering to the answer with Klaxon. It seems to do exactly what I want, but Klaxon's Parser is deprecated. Commented Jan 30, 2022 at 21:52
  • in jackson you have org.bson.Document which acts like a sort of map. You can do .get and other things with it. I'm sure that all the others have similar objects. Commented Jan 30, 2022 at 22:09
  • Most, if not all, of the JSON parsers you list have generic ways to parse as well without the need to define the class Commented Jan 31, 2022 at 12:22

2 Answers 2

10

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

val json: Map<String, JsonElement> = Json.parseToJsonElement(jsonstring).jsonObject
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.