gpt4 book ai didi

java - Fuel、Kotlin、Gson,应为 BEGIN_ARRAY 但在第 1 行是 BEGIN_OBJECT

转载 作者:搜寻专家 更新时间:2023-11-01 09:30:16 24 4
gpt4 key购买 nike

我正在尝试像这样解析 JSON 字符串:

{
"count": 1,
"items": [
{
"organization_id": 6972979,
"organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
}
]
}

还有 Kotlin 类:

class LoremModel {
var count: Int? = null
var items: List<Lorem>? = null

class Lorem {
var organization_id: Int? = null
var organization_name: String? = null

constructor(organization_id: Int?, organization_name: String?) {
this.organization_id = organization_id
this.organization_name = organization_name
}
}

class ListDeserializer : ResponseDeserializable<List<LoremModel>> {
override fun deserialize(content: String) = Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)
}
}

燃料部分:

Fuel.get("/lorem/search", listOf("keywords" to  keyword, "category" to category, "pageNum" to "1", "pageSize" to "10")).
responseObject(LoremModel.ListDeserializer()) { request, _, item ->
}

但是我得到一个错误:

[Failure: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $]

如何解决?

最佳答案

你的json

{
"count": 1,
"items": [
{
"organization_id": 6972979,
"organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
}
]
}

代表一个 JSON 对象而不是一个 JSON 数组。

因此,与其尝试将其反序列化为 LoremModel 对象的 List 类型

Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)

您应该将其反序列化为 LoremModel 类型的对象。所以你可以这样做:

Gson().fromJson(content, LoremModel::class.java)

关于java - Fuel、Kotlin、Gson,应为 BEGIN_ARRAY 但在第 1 行是 BEGIN_OBJECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47691915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com