在我使用Retrofit的Android应用程序中,我正在尝试反序列化具有包装项目列表的外部对象的JSON。我正在使用带有Retrofit实例的GsonConverterFactory来反序列化JSON。我创建了一个自定义反序列化程序,以仅从响应中提取项目列表,因此我不必创建父包装类。我以前用 Java 做过这件事,但我无法让它与 Kotlin 一起工作。调用 ItemsService 来获取 Items 时,我收到以下异常:java.lang.IllegalStateException:预期BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处BEGIN_OBJECT
我的反序列化程序是否有问题,或者我如何使用 Gson 和 Retrofit 配置它?我还有什么做错事吗?
杰森:
{
"items" : [
{
"id" : "item1"
},
{
"id" : "item2"
},
{
"id" : "item3"
}
}
反序列化器:
class ItemsDeserializer : JsonDeserializer<List<Item>> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): List<Item> {
val items: JsonElement = json!!.asJsonObject.get("items")
val listType= object : TypeToken<List<Item>>() {}.type
return Gson().fromJson(items, listType)
}
}
项目:
data class Item (val id: String)
项目服务:
interface ItemsService {
@GET("items")
suspend fun getItems(): List<Item>
}
服务工厂:
object ServiceFactory {
private const val BASE_URL = "https://some.api.com"
private val gson = GsonBuilder()
.registerTypeAdapter(object : TypeToken<List<Item>>() {}.type, ItemsDeserializer())
.create()
fun retrofit(): Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
val itemsService: ItemsService = retrofit().create(ItemsService::class.java)
}
哦,这是一个非常常见的错误。您必须使用TypeToken.getParameterized
创建参数化类型。所以你必须把object : TypeToken<List<Item>>() {}.type
改成TypeToken.getParameterized(List::class.java, Item::class.java).type
class ItemsDeserializer : JsonDeserializer<List<Item>> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): List<Item> {
val items: JsonElement = json!!.asJsonObject.get("items")
val listType= TypeToken.getParameterized(List::class.java, Item::class.java).type
return Gson().fromJson(items, listType)
}
}
private val gson = GsonBuilder()
.registerTypeAdapter(TypeToken.getParameterized(List::class.java, Item::class.java).type, ItemsDeserializer())
.create()