Rajesh
Rajesh

Reputation: 87

How to use chaining in Kotlin to parse JSON like python

Suppose i have a JSON as below:

sampleJSON = {

"key1": {
        "nestedkey1": "nestedvalue1",
        "nestedkey2": "nestedvalue2"
},
"key2": {
        "nestedkey3": "nestedvalue3",
        "nestedkey4": "nestedvalue4"
}   
}

Now i want to access value of nestedkey2 so in python(as it is also python dictionary) we can access like,

print(sampleJSON.get("key1").get("nestedkey2"))

But in kotlin, we have to explicitely first get outer JSON object and then the inner value like this:

val outerJO = JSONObject(sampleJSON)
val innerJO = outerJO.getJSONObject("key1")
println(innerJO.get("nestedkey2"))

Is there any way to use chaining like python in Kotlin to access nested JSON objects? Any library which can do it?

Upvotes: 1

Views: 417

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17721

That's easy to achieve using extension functions. For example with Gson library:

import com.google.gson.JsonElement
import com.google.gson.JsonParser

fun main() {
    val jsonString = """
        {

"key1": {
        "nestedkey1": "nestedvalue1",
        "nestedkey2": "nestedvalue2"
},
"key2": {
        "nestedkey3": "nestedvalue3",
        "nestedkey4": "nestedvalue4"
}   
}
    """
    val json = JsonParser().parse(jsonString)
    val result = json["key1"]["nestedkey2"] // Even shorter that in Python

    println(result)
}

private operator fun JsonElement.get(key: String) = this.asJsonObject.get(key)

Upvotes: 4

Related Questions