![](/img/trans.png)
[英]Using Klaxon JSON for Android how can I get the following JSON in to a ListView?
[英]How do I parse the json from thingspeak to get the field value using klaxon on android studio?
我正在使用 thingspeak,並且我已經成功地讓 thingspeak 使用 okhttp 獲取 json 數據,但我不知道如何使用 klaxon 正確解析它。
這是代碼
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!")
}
})
這是來自 thingspeak 的 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 的 field1 的值,但我不知道該怎么做,因為我很愚蠢。 但我希望有人能告訴我如何正確使用 klaxon 來獲取 json 數據。
對於 Klaxon,您需要創建一個代表 JSON 結構的 class。 fe 如果你得到一個 JSON :
{
"username": "admin",
"password": "admin"
}
你想做一個看起來像這樣的 class :
class myClass(val username:String, val password:String)
然后,您可以像正在做的那樣解析它。 對於您的 JSON,您需要更大的 Class。 為簡單起見,我將只為供稿制作一個 class ,為頻道制作一個 class :
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)
然后你可以使用這個 class 來解析你的 JSON:
class Thingspeak(val channel: Channel, val feeds: ArrayList<Feed>)
請讓我知道它是否對您有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.