Android Kotlin凌空抽射如何从JSONArray获得价值 [英] Android Kotlin Volley How to get value from JSONArray

查看:49
本文介绍了Android Kotlin凌空抽射如何从JSONArray获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在";media_Gallery_Entries&Quot;JSONArray中获取";file";通过volley for循环

凌空抽射

val item = ArrayList<RecyData>()
val jsonRequest = object : JsonObjectRequest(Request.Method.GET, url, null,

    Response.Listener { response ->

       try {

            val jsonArrayItems = response.getJSONArray("items")
            val jsonSize = jsonArrayItems.length()

            for (i in 0 until jsonSize) {
                val jsonObjectItems = jsonArrayItems.getJSONObject(i)
                val pName = jsonObjectItems.getString("name")
                val pPrice = jsonObjectItems.getInt("price")
                item.add(RecyData(pName, pPrice, pImage))
            }
       } catch (e: JSONException) {
             e.printStackTrace()
       }

数据

{
   "items": [
       {
           "id": 1,
           "sku": "10-1001",
           "name": "item01",
           "price": 100,
           "media_gallery_entries": [
               {
                   "id": 1,
                   "file": "//1/0/10-28117_1_1.jpg"
               }
           ]
       }
   ]
}

推荐答案

不用手动JSON解析总是容易出错,您可以使用一些解析库,例如Gson,它经过了很好的测试,不太可能导致任何问题

若要使用Gson,首先需要在生成中添加依赖项。gradle作为

implementation 'com.google.code.gson:gson:2.8.7'

现在定义映射到JSON响应的Kotlin类型

class Media(
        val id: Int,
        val file: String
)

class Entry(
        val id: Int,
        val sku: String,
        val name: String,
        val price: Int,
        val media_gallery_entries: List<Media>
)

现在在响应侦听器中只需执行

try{
    val jsonArrayItems = response.getJSONArray("items")
    val token = TypeToken.getParameterized(ArrayList::class.java, Entry::class.java).type
    val result:List<Entry> = Gson().fromJson(jsonArrayItems.toString(), token)
    // Do something with result
}
catch (e: JSONException) {
    e.printStackTrace()
}

这篇关于Android Kotlin凌空抽射如何从JSONArray获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆