You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Retrofit API响应中提取所有Variants到ArrayList及其他实现方案

问题描述

我通过Retrofit获取了商品列表API响应(JSON结构如下),当前用Kotlin代码处理响应并插入Room数据库,现在需要把响应中data数组里每个商品的variants列表提取出来,汇总到一个ArrayList中。想知道如何用for循环实现,以及有没有其他基于数据结构/算法的实现方式。

API响应示例

{"error": false,"total": "20","total_page_no": 1,"current_page_no": 1,"data": [{"id": "4241","row_order": "0","name": "Shivaji Ponni Rice","tax_id": "1","slug": "Shivaji Ponni Rice","category_id": "52","subcategory_id": "196","indicator": "1","manufacturer": null,"made_in": "Shivaji Ponni Rice","return_status": "1","cancelable_status": "1","till_status": "received","image": "http://www.pasumai.co.in/upload/default-image/default-image.png","other_images": [],"description": "The best variety of rice is determined by its amount of usage. In that aspect, The Shivaji brand Matured variety of rice is highly recommended for every household. It is manufactured in the special unit and this variety is the rice matured between the months of august of one year to June of the succeeding year. It can be easily cooked and hence saves time. Perfect in shape, it is easy to digest and is suitable for any family possessing people of all age groups. Nevertheless, they produce a surplus since it is the matured variety of rice. Used by most of the families makes it the highest-selling variety of rice","status": "1","popular": "0","date_added": "2022-07-24 07:50:28","return_max_days": "0","tax": "0","price": "1500","tax_title": "GST","tax_percentage": "0","is_favorite": false,"is_notify_me": false,"variants": [{"id": "7477","product_id": "4241","type": "packet","measurement": "26","measurement_unit_id": "1","price": "1500","discounted_price": "1350","serve_for": "Available","stock": "20","stock_unit_id": "6","image": "upload/default-image/default-image.png","moq": "5","varient_status": "1","measurement_unit_name": "kg","stock_unit_name": "pcs","cart_count": "0","is_notify_me": false}]} ,{"id": "4243","row_order": "0","name": "Semmoli Kichadi Ponni","tax_id": "1","slug": "Semmoli Kichadi Ponni","category_id": "52","subcategory_id": "196","indicator": "1","manufacturer": null,"made_in": "Semmoli Kichadi Ponni","return_status": "1","cancelable_status": "1","till_status": "received","image": "http://www.pasumai.co.in/upload/default-image/default-image.png","other_images": [],"description": "Nei Kichadi Ponni rice is best suited for all occasions. It is well known for premium quality, light weight, excellent aroma and taste. Its gluten free, does not contain any artificial flavours or preservatives","status": "1","popular": "0","date_added": "2022-07-24 07:50:28","return_max_days": "0","tax": "0","price": "1600","tax_title": "GST","tax_percentage": "0","is_favorite": false,"is_notify_me": false,"variants": [{"id": "7474","product_id": "4243","type": "packet","measurement": "26","measurement_unit_id": "1","price": "1600","discounted_price": "1420","serve_for": "Available","stock": "20","stock_unit_id": "6","image": "upload/default-image/default-image.png","moq": "5","varient_status": "1","measurement_unit_name": "kg","stock_unit_name": "pcs","cart_count": "0","is_notify_me": false}]}]}

当前处理代码

fun productlist() = viewModelScope.launch(Dispatchers.IO) {
    productist.collectLatest {
        when(it) {
            Resource.Empty -> {
                Log.e("catdata",""+"empty")
            }
            is Resource.Failure -> {
                Log.e("catdata",""+"failure")
            }
            Resource.Loading -> {

            }
            is Resource.Success -> {
                val response = it.value
                productsDao.insertProducts(response.data)
            }
        }
    }
}
解决方案

1. 基础for循环实现

直接嵌套遍历商品列表和每个商品的变体列表,将变体逐个添加到目标集合中:

is Resource.Success -> {
    val response = it.value
    productsDao.insertProducts(response.data)
    
    // 初始化存放所有变体的ArrayList
    val allVariants = ArrayList<Variant>() // 这里的Variant是你的实体类
    
    // 遍历每个商品
    for (product in response.data) {
        // 处理变体列表可能为空的情况,避免空指针
        product.variants?.let { variants ->
            // 遍历当前商品的变体并添加到集合
            for (variant in variants) {
                allVariants.add(variant)
            }
        }
    }
    
    // 后续可对allVariants进行操作,比如插入到Room的变体表
}

2. Kotlin函数式风格实现(更简洁)

利用Kotlin集合的flatMap函数,它可以将嵌套集合平铺为单一集合,完美适配这种提取嵌套列表的场景:

is Resource.Success -> {
    val response = it.value
    productsDao.insertProducts(response.data)
    
    // 用flatMap直接提取所有变体,处理空列表情况
    val allVariants = response.data.flatMap { product -> product.variants ?: emptyList() }
    // 如果需要ArrayList类型,直接转换即可
    val variantsArrayList = ArrayList(allVariants)
    
    // 后续操作
}

如果想直接将结果存入预先初始化的ArrayList,可使用flatMapTo:

val allVariants = ArrayList<Variant>()
response.data.flatMapTo(allVariants) { it.variants ?: emptyList() }

flatMap的核心逻辑是:对每个商品取出其变体列表,再将所有列表合并为一个新的List,代码更简洁且可读性强。


内容的提问来源于stack exchange,提问作者SasidharanIOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 16:27:23