如何使用gson将字段1的值作为可变量的整数



我一直在使用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 rnRules : 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调试显示存在的值有人知道我如何把它的值输入到代码中,这样我就可以把它作为变量使用了吗?我真的很困惑,不知道该怎么办。提前谢谢。

试试这个

json.feeds[0].field1

最新更新