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

如何用Kotlin Serializer序列化嵌套列表并映射为Product数据类?

将嵌套列表映射为Product对象列表的解决方案

你可以通过类型安全的映射转换实现嵌套列表到Product对象的转换,核心思路是遍历Response.body中的每个子列表,按固定索引取出对应字段并转换为Product所需类型。以下是具体实现步骤:

1. 解析JSON到Response对象

先用kotlinx.serialization把JSON字符串解析为你定义的Response实例:

import kotlinx.serialization.json.Json

val jsonString = """你的目标JSON字符串"""
val response = Json.decodeFromString<Response>(jsonString)

2. 映射嵌套列表到Product列表

由于子列表的元素顺序与Product字段一一对应,我们可以直接按索引取值并做类型转换,同时加入安全处理避免类型转换异常:

fun List<Any>.toProduct(): Product? {
    // 先校验子列表元素数量是否匹配Product字段数
    if (size != 18) return null

    return try {
        Product(
            title = this[0] as String,
            color = this[1] as String,
            price = this[2] as String,
            id = (this[3] as Number).toInt(),
            type = this[4] as String,
            ean = this[5] as String,
            count = (this[6] as Number).toInt(),
            weight = (this[7] as Number).toInt(),
            pricePerPiece = (this[8] as Number).toFloat(),
            countryOfOrigin = this[9] as String,
            expiry = this[10] as String,
            Description = this[11] as String, // 注意字段首字母大小写要与数据类一致
            nettWeight = (this[12] as Number).toInt(),
            link = this[13] as String,
            date = this[14] as String,
            isUnavailable = this[15] as Boolean,
            isCooked = this[16] as Boolean,
            isFruit = this[17] as Boolean
        )
    } catch (e: ClassCastException) {
        // 捕获类型转换异常,返回null跳过无效数据
        null
    }
}

// 转换整个嵌套列表为Product对象列表
val productList = response.body.mapNotNull { it.toProduct() }

关键注意事项

  • 索引对应关系:必须严格遵循JSON中子列表的元素顺序匹配Product字段,顺序变动会直接导致映射错误。
  • 类型安全:数字类型统一先转为Number再转具体类型(Int/Float),适配JSON中数字可能被解析为Double/Long的情况;用try-catch或as?处理类型不匹配的异常,避免程序崩溃。
  • 字段名一致性:确保Product的字段名(如Description首字母大写)与映射逻辑完全对应,避免赋值错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:27:35