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
相关产品推荐
相关产品推荐

