如何在Kotlin中使用Retrofit在Json中访问嵌套数组或子数组

问题描述

这是我的Json数据,我想在各节中访问Item数组。我剪切了json,因为获取数组的方式太长了,我得到arrayOutOfBound错误。

{
   "status":"true","sections":[
      {
         "type":"items","label":"Just Arrived ","items":[
            {
               "id":16676,"item_title":"Beauty Clinic Antibacterial Hand Sanitizer Non Sticky & Moisturizer,225ML","currency":"AED","mainprice":15,"price":15,"deal_enabled":"no","market_price":35,"discount_percentage":57,"valid_till":"","quantity":46,"cod":"yes","liked":"no","grade":"Brand New","grade_color":"#00af41","report":"no","shipping_time":"Three business days","image":"https:\/\/cartlow.com\/media\/items\/thumb350\/1584281034_6.jpeg"
            },{
               "id":2561,"item_title":"Samsung Galaxy M10 Dual SIM - 16GB,2GB RAM,4G LTE,Charcoal Black - UAE Version","mainprice":329,"price":329,"market_price":449,"discount_percentage":27,"quantity":1,"grade":"Pre-owned","grade_color":"#ff671b","image":"https:\/\/cartlow.com\/media\/items\/thumb350\/1572942674_6.jpg"
            },{
               "id":15944,"item_title":"OnePlus 7 Pro 256GB 8GB RAM 4G LTE - Almond","mainprice":1999,"price":1999,"market_price":2999,"discount_percentage":33,"image":"https:\/\/cartlow.com\/media\/items\/thumb350\/195d0fc3aa4198faebc46654eed1cc83.jpg"
            },{
               "id":9806,"item_title":"OnePlus 7T Pro - 256GB,8GB RAM,4G LTE - Haze Blue","mainprice":1990,"price":1990,"market_price":2799,"discount_percentage":29,"quantity":9,"image":"https:\/\/cartlow.com\/media\/items\/thumb350\/f76fa006c5574ac25d6a257b7558dce3.jpg"
            },

我正在使用Kotlin语言和Retrofit Api访问此数据,但无法获取此数组。我的Model类是这些

data class HomeResponseModel(
    val banner: List<Banner>? = null,val category: List<Category>? = null,val daily_deals: DailyDeals? = null,val home_message: String? = null,val home_message_color: String? = null,val sections: List<Section>? = null,val status: String? = null
)
data class Section(
    val category: String? = null,val items: List<Item>? = null,val label: String? = null,val type: String? = null
)
data class Item(
    val category: String? = null,val cod: String? = null,val currency: String? = null,val deal_enabled: String? = null,val discount_percentage: Int? = null,val grade: String? = null,val grade_color: String? = null,val id: Int? = null,val image: String? = null,val image_color: String? = null,val item_title: String? = null,val liked: String? = null,val mainprice: Int? = null,val market_price: Int? = null,val name: String? = null,val price: Int? = null,val product_id: String? = null,val quantity: Int? = null,val report: String? = null,val section_category: String? = null,val section_id: String? = null,val section_label: String? = null,val section_type: String? = null,val shipping_time: String? = null,val title_color: String? = null,val valid_till: String? = null
)

这是我在获取响应中的简单改造代码

val retrofitBuilder = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://stg.cartlow.com/")
            .build()
        val jsonApi = retrofitBuilder.create(ApiDataParsing::class.java)

        jsonApi.getHome(
            null,"android",18,"UAE","AED","Arabic"

        ).enqueue(object : Callback<HomeResponseModel>
        {
            override fun onFailure(call: Call<HomeResponseModel>,t: Throwable) {
                Log.e("Error","Section List Error! $t")
            }
            override fun onResponse(call: Call<HomeResponseModel>,response: Response<HomeResponseModel>) {
                sectionAdapter = SectionAdapter(response.body()?.Section as List<Section>)
                sectionAdapter.notifyDataSetChanged()
                section_list.adapter = sectionAdapter
                }

        })
    }

在我的RecyclerView适配器类中,由于不知道如何获取物品而出现IndexOutOfBound错误


var categoryList = categoryList[position].items?.get(position)

解决方法

您的代码给出IndexoutofBound异常,因为您正在使用Index(position)访问“ List />”中的元素,该元素大于“ List />”的大小。因此,您需要首先检查索引(位置)是否小于数组/列表的大小。

if(position< categoryList[position].items?.size)
var categoryList = categoryList[position].items?.get(position)

或 如果您想要物品清单,则可以从以下响应中获取物品清单


var itemList= categoryList[position].items

然后您可以根据需要使用itemList

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...