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

Android中Moshi+Retrofit解析JSON报错:Expected a string but was BEGIN_ARRAY

解决Moshi解析JSON时抛出"Expected a string but was BEGIN_ARRAY at path $"异常

解析JSON数据到Kotlin数据类时,API调用抛出异常:Expected a string but was BEGIN_ARRAY at path $。起初确认JSON响应结构与Moshi预期的模型类匹配,但问题仍未解决。

后续排查发现,将NetworkIncome类中的BigDecimal和LocalDateTime字段替换为String类型后,解析成功。由此定位问题根源:未正确配置Moshi自定义适配器,之前编写的适配器未被Moshi识别,只能通过手动转换格式解决,实现方式不够优雅。

最终通过编写正确的BigDecimal和OffsetDateTime自定义适配器,并将其添加到Moshi构建器中,彻底解决了问题。

自定义适配器代码

BigDecimal适配器

class BigDecimalAdapter {
    @FromJson
    fun stringToBigDecimal(value: String): BigDecimal = BigDecimal(value)

    @ToJson
    fun bigDecimalToString(value: BigDecimal): String = value.toString()
}

OffsetDateTime适配器

class OffsetDateTimeAdapter {
    @FromJson
    fun toDateTime(value: String) = OffsetDateTime.parse(value)

    @ToJson
    fun fromDateTime(value: OffsetDateTime) = value.toString()
}

配置Moshi构建器

Moshi.Builder()
        .add(BigDecimalAdapter())
        .add(OffsetDateTimeAdapter())
        .addLast(KotlinJsonAdapterFactory())
        .build()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:41:23