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

Kotlin中如何遍历JSON Object生成的Data Class或转数组适配RecyclerView

解决方案

方案一:反射遍历Rates对象生成集合

利用Kotlin反射直接获取Rates类的所有属性,将属性名作为货币类型、属性值作为货币金额,生成目标集合:

fun Rates.toCurrencyList(): List<CurrencyAndTypeList> {
    return this::class.declaredMemberProperties
        .filterIsInstance<KProperty1<Rates, Double>>() // 过滤出Double类型的货币属性
        .map { property ->
            CurrencyAndTypeList(
                currencyAmount = property.get(this),
                currencyType = property.name
            )
        }
}

用法:拿到Rates实例后,直接调用rates.toCurrencyList()即可得到适配RecyclerView的列表。

注意:若Rates存在非Double类型的属性,需调整过滤规则;反射在性能敏感场景下需谨慎使用,但列表展示场景完全适用。

方案二:解析JSON时直接转换(更高效)

若还未完成JSON解析,可跳过Rates类的生成,直接从JSON Object转换为目标集合,避免反射开销:

用Gson实现

val gson = Gson()
// 假设原始JSON字符串为jsonStr,其中"rates"是目标Object字段
val rootJson = gson.fromJson(jsonStr, JsonObject::class.java)
val ratesJson = rootJson.getAsJsonObject("rates")

val currencyList = mutableListOf<CurrencyAndTypeList>()
for ((currencyType, amountJson) in ratesJson.entrySet()) {
    currencyList.add(
        CurrencyAndTypeList(
            currencyAmount = amountJson.asDouble,
            currencyType = currencyType
        )
    )
}

用Moshi实现

val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(JsonObject::class.java)
val rootJson = jsonAdapter.fromJson(jsonStr)
val ratesJson = rootJson?.getAsJsonObject("rates")

val currencyList = ratesJson?.entrySet()?.map { entry ->
    CurrencyAndTypeList(
        currencyAmount = entry.value.asDouble,
        currencyType = entry.key
    )
} ?: emptyList()

方案三:手动转换(性能最优)

如果Rates的属性数量较少且固定,可手动编写转换方法,完全避免反射或JSON解析额外开销:

fun Rates.toCurrencyListManual(): List<CurrencyAndTypeList> {
    return listOf(
        CurrencyAndTypeList(AED, "AED"),
        CurrencyAndTypeList(AFN, "AFN"),
        CurrencyAndTypeList(ALL, "ALL"),
        CurrencyAndTypeList(AMD, "AMD"),
        CurrencyAndTypeList(ANG, "ANG"),
        CurrencyAndTypeList(AOA, "AOA"),
        CurrencyAndTypeList(ARS, "ARS"),
        // 依次添加剩余货币属性...
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:00:17