How do I parse the json from thingspeak to get the field value using klaxon on android studio?

644 Views Asked by At

I'm using thingspeak and I have successfully got thingspeak to fetch the json data using okhttp but I don't know how to parse it correctly using klaxon.

Here is the code

private fun funButton1() {
    println("Attempting to get JSON data!")
    val url = "https://api.thingspeak.com/channels/1029606/feeds.json?results=1"

    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback {
        override fun onResponse(call: Call, response: Response) {
            val body = response.body?.string()
            println(body)
            class feeds (val field1: String)
            val result = Klaxon()
                .parse<feeds>(body.toString())

            textView.text = result
        }
        override fun onFailure(call: Call, e: IOException) {
            println("Failed to execute request!")
        }

    })

This is the json data from the thingspeak

    {
  "channel": {
    "id": 1029606,
    "name": "LED ",
    "description": "Acts as a medium for the phone and arduino \r\nRules : 1 = LED ON 0 = LED OFF ",
    "latitude": "0.0",
    "longitude": "0.0",
    "field1": "LED STATUS",
    "created_at": "2020-04-01T17:19:03Z",
    "updated_at": "2020-04-01T17:20:39Z",
    "last_entry_id": 25
  },
  "feeds": [
    {
      "created_at": "2020-05-11T02:58:07Z",
      "entry_id": 25,
      "field1": "1"
    }
  ]
}

Im trying to get the value of field1 which the value is one but I don't know how I'm supposed to do that because im stupid. But I'm hoping that someone could show me how to use klaxon properly to get the json data.

1

There are 1 best solutions below

2
On

For Klaxon, you'll need to create a class which represent the structure of your JSON. f.e. if you get a JSON with:

{
    "username": "admin",
    "password": "admin"
}

you wanna make a class which looks like that:

class myClass(val username:String, val password:String)

Then, you can parse it like you are doing. For your JSON, you'll need a bigger Class. For the Sake of simplicity, I'll just make a class for feeds and a class for the channel:

class Feed(val created_at:String, val entry_id: Int, val field1:String)
class Channel(val id: Int, val name: String, val description: String, val latitude: String, val longitude:String, val field1: String, val created_at: String, val updated_at: String, val last_entry_id: Int)

Then you can use this class to parse your JSON:

class Thingspeak(val channel: Channel, val feeds: ArrayList<Feed>)

Please let me know if it worked for you!