如何将 JsonObject 转换为类模型 kotlin android



>我从服务器接收一些数据并将其转换为JsonArray。我想也许我可以将这个数组转换为类对象的普通数组,但我没有设法做到。我试着这样做:

val testArray = tpsObject.getAsJsonObject("questions")[tpsSelection[0].toString()].asJsonArray
for (i in 0 until testArray.size()) {
Log.i("m",Gson().fromJson(testArray.get(i).asJsonObject.toString(),QuestionModel::class.java).question.toString())
}

但我收到错误:

com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonArray

另一方面,我可以像这样循环显示 JsonArray 的所有元素:

Log.i("m",testArray.get(i).asJsonObject.toString())

我也尝试这样做:

val jsonParser = JsonParser.parseString(testArray.get(i).asJsonObject.toString())
val model: QuestionModel = Gson().fromJson(jsonParser, QuestionModel::class.java)

但我收到类似的错误。所以也许有人知道如何解决这个问题?

更新

my json:
"1": [
{
"answer_options": [
{
"id": 216,
"answer": "some text"
},
{
"id": 217,
"answer": "some text"
},
{
"id": 218,
"answer": "some text"
},
{
"id": 219,
"answer": "some text"
},
{
"id": 220,
"answer": "some text"
}
],
"id": 949,
"question": "some text"
},
...
{
"answer_options": [
{
"id": 216,
"answer": "some text"
},
{
"id": 217,
"answer": "some text"
},
{
"id": 218,
"answer": "some text"
},
{
"id": 219,
"answer": "some text"
},
{
"id": 220,
"answer": "some text"
}
],
"id": 949,
"question": "some text"
},
],

我的模型类:

class QuestionModel {
@SerializedName("question")
@Expose
var question: String? = null
@SerializedName("id")
@Expose
var id: Int? = null
@SerializedName("answer_options")
@Expose
var answer_options: JsonObject? = null
}

也许这将有助于找到解决方案

我建议你改用kotlinx.serialization,但为了不是一个典型的StackOverflow用户说"A是错的,做B",我也会尝试解决你的问题。

你真的需要发布你的JSON(或其片段(和类定义,否则很难帮助你。根本问题是你给 Gson 一个数组,但它想要一个对象。也许您实际上在 JSON 中使用了 2d 数组?给定堆栈跟踪,这将更容易调试。

此外,在反序列化 JsonObject之前,您似乎正在调用 .toString((,这意味着您正在重新序列化为 Json,然后再次重新序列化......但是为什么?

最新更新