Android Kotlin Volley 如何从 JSONArray 获取值

Android Kotlin Volley How to get value from JSONArray

我想通过 Volley for 循环在“media_gallery_entries”JSONArray 中获取“文件”

Volley

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()
       }

Data

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

val pPrice = jsonObjectItems.getInt("price")这一行

之后尝试这段代码
 val mediaEntryArr = jsonObjectItems.getJSONArray("media_gallery_entries")
                for(j in 0 until mediaEntryArr.length()){
                    val mediaEntryObj = mediaEntryArr.getJSONObject(j)
                    val id = mediaEntryObj.getString("id")
                    val file = mediaEntryObj.getString("file")
                    Log.e("mediaEntry----",""+ Gson().toJson(mediaEntryObj))
                    Log.e("id----",""+ id)
                    Log.e("file----",""+ file)
                }

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

要使用 Gson,您首先需要在 build.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()
}