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

构造适配Gson的Kotlin类解析TMDb分级认证JSON响应报错问题

问题解决方案

报错根因

JSON响应中certifications字段为对象类型(键是动态的国家编码字符串,值是对应国家的影视分级列表),但你原代码中将该字段声明为List<Country>数组类型,Gson解析时类型不匹配,因此抛出Expected BEGIN_ARRAY but was BEGIN_OBJECT错误。

调整后的类结构

针对动态键的JSON结构,直接使用Map承接即可,无需为每个国家单独定义类,也不需要冗余的Country类:

class Certifications {
    // 键:国家编码(如CA、NL),值:对应国家的分级列表
    var certifications: Map<String, List<Certification>>? = null
}

class Certification {
    var certification: String? = null
    var meaning: String? = null
    var order: Int = 0
}

修改后直接执行原有解析代码即可正常解析:

val thing = gson.fromJson(body, Certifications::class.java)

数据使用示例

  • 获取指定国家的分级列表:
    // 拿加拿大的分级数据
    val canadaRatings = thing.certifications?.get("CA")
    
  • 遍历所有国家的分级数据:
    thing.certifications?.forEach { (countryCode, ratingList) ->
        // 处理对应国家的分级数据
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:45:00