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

如何使用Moshi解析继承自ArrayList的类?

解决Moshi解析继承ArrayList的类时的JsonDataException错误

错误com.squareup.moshi.JsonDataException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $的核心原因是:你定义的CarSelection继承自ArrayList<CarItem>,但Moshi默认会把自定义类当作对象解析,而接口返回的JSON是数组格式,两者不匹配导致报错。

下面提供两种可行的解决办法:

方案一:直接用List/ArrayList作为接口返回类型

这是最省心的方式,不需要改动CarSelection类,直接在Retrofit接口里把返回类型换成List<CarItem>或者ArrayList<CarItem>:

interface MyRemoteService {
    @GET("你的接口路径")
    suspend fun getCarList(): List<CarItem> // 也可以用ArrayList<CarItem>
}

如果一定要用到CarSelection,拿到数据后转一下就行:

val carList = remoteService.getCarList()
val carSelection = CarSelection().apply { addAll(carList) }

方案二:给CarSelection写自定义Moshi适配器

如果必须让Retrofit直接返回CarSelection,就得给Moshi加个自定义适配器,告诉它怎么把JSON数组转成CarSelection对象:

  1. 先写适配器类:
class CarSelectionAdapter {
    @FromJson
    fun fromJson(carItems: List<CarItem>): CarSelection {
        return CarSelection().apply { addAll(carItems) }
    }

    @ToJson
    fun toJson(carSelection: CarSelection): List<CarItem> {
        return carSelection
    }
}
  1. 创建Moshi实例时注册这个适配器:
fun getRemoteService(baseUrl :String, client : OkHttpClient): MyRemoteService {
    val moshi = Moshi.Builder()
        .add(CarSelectionAdapter())
        .build()
        
    return Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(client)
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .build()
        .create(MyRemoteService::class.java)
}
  1. 这时候接口就可以直接返回CarSelection了:
interface MyRemoteService {
    @GET("你的接口路径")
    suspend fun getCarSelection(): CarSelection
}

内容的提问来源于stack exchange,提问作者S.P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:40:30