简体   繁体   中英

Get data from nested json using GSON

Can you, please, help me understand how to parse data from nested json file using GSON. I have looked at other similar question posted, but don't see where have i made a mistake. I'm trying to get id, user, technician and an account from my json file.

My JSON file look like this:

{
  "operation": {
    "result": {
      "message": "successful",
      "status": "done"
    },
    "details": [
      {
        "id": "106818",
        "user": "Leona",
        "technician": "45441",
        "account": "Inc",
        "status": "Open"
      }
    ]
  }
}

Code:

        val url = "https://myURL"
        val request = Request.Builder().url(url).build()

        val client = OkHttpClient()
        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                println("Failed - onFailure")
            }

            override fun onResponse(call: Call, response: Response) {
                val body = response?.body()?.string()
                println(body)

                val gson = GsonBuilder().create()
                gson.fromJson(body, HomeFeed::class.java)

               }

        })

    }
}


class HomeFeed(val details: List<Details>)
class Details(val id: String, val user:String, val technician:String, val account:String)   

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.kotlinjsontube, PID: 10905
    java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.Collection.size()' on a null object reference
        at com.example.kotlinjsontube.MainAdapter.getItemCount(MainAdapter.kt:13)

Thank you.

Your response modeled into a POJO class:

Model.kt

data class Model(
  val operation: Operation,
  val details: List<Detail>
)

data class Operation(
  val result: Result
)

data class Result(
  val message: String,
  val status: String
)



data class Detail(
  val id: String,
  val user: String,
  val technician: String,
  val account: String,
  val status: String
)

Class where you make the request:

val url = "https://myURL"
val request = Request.Builder().url(url).build()

val client = OkHttpClient()
client.newCall(request).enqueue(object :Callback{
    override fun onFailure(call: Call, e: IOException) {
        println("Failed - onFailure")
    }

    override fun onResponse(call: Call, response: Response) {
        val body = response?.body()?.string()
        println(body)

        val gson = GsonBuilder().create()
        gson.fromJson(body, Model::class.java)

       }

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM