Reputation: 55
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.
Upvotes: 2
Views: 1409
Reputation: 1234
Your response modeled into a POJO class:
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
)
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)
}
})
Upvotes: 4