-3

I have JSON:

{
   "results":[
      {
         "age":21,
         "source":{
            "apple":"green"
         }
      }
   ],
   "stat":"ok"
}

How can I assign the age value to the user_age variable in JSON in Kotlin? Or output the age value in JSON?

  • Give me a code please – Mike Dayson Jun 03 '20 at 11:22
  • Hi Mike, Welcome to Stack Overflow, Please read: [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236). This question is really low quality. The grammar is poor, the formatting is off, but most importantly, you didn't show any effort in trying to solve your own important. That's really important here. We like to see people's research, attempts, failing code, etc. Otherwise this just devolves into an unsustainable free code-writing service, which it's not. Please see [idownvotedbecau.se/noresearch](https://idownvotedbecau.se/noresearch/) – Animesh Sahu Jun 03 '20 at 11:24
  • 3
    Does this answer your question? [How to parse JSON in Kotlin?](https://stackoverflow.com/questions/41928803/how-to-parse-json-in-kotlin) – denvercoder9 Jun 03 '20 at 11:25
  • Welcome to Stack Overflow. What extactly are you trying to ask? Post what have you tried? – Durga M Jun 03 '20 at 11:26

2 Answers2

0

Assuming the JSON in String variable str. You can fetch age using below code:

    val root = JSONObject(str)
    val array = root.optJSONArray("results")
    val age = array!!.getJSONObject(0).optInt("age",0) //default 0
Alpha 1
  • 4,118
  • 2
  • 17
  • 23
0

For future reference. This is how you read a json in kotlin.

import com.fasterxml.jackson.databind.ObjectMapper


fun main() {
    val readValue: Domain = ObjectMapper().readValue(readString, Domain::class.java)
}

data class Domain(
        val stat: String? = null,
        val results: List<Result>? = null
)

data class Result(
        var age: Int? = null,
        var source: Source? = null
)

data class Source(
        var apple: String? = null
)
Deepak
  • 171
  • 1
  • 12