首页 > 解决方案 > 我如何将字段 1 值作为 gson 的整数变量?

问题描述

我一直在使用thingspeak,我一直在尝试解析Json数据并让字段1在文本视图上被读取,但我无法将它作为一个变量来使用。

这里有一些代码可以帮助你

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)

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

这是 kotlin 代码,这是我用于 gson 的 calsses

class Json(val feeds: List<Feed>)
class Feed(val field1: Int)

这是json数据

{
  "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"
    }
  ]
}

现在你可以看到字段 1 的数据是 1 是我试图用作变量的东西,但我不确定如何。gson 代码确实会解析它或其他东西(我不确定这里是否有图像) gson 调试显示值存在 所以有谁知道我如何将它的值放入代码中,以便我可以将它用作变量我是很困惑,不知道该怎么办。提前致谢。

标签: jsonkotlingsonokhttp

解决方案


试试这个

json.feeds[0].field1


推荐阅读