我无法将 JSON 数组转换为 GroupModel
数组。下面是我使用的 JSON:
[{
"description":"My expense to others",
"items":["aaa","bbb"],
"name":"My Expense"
},
{
"description":"My expense to others","
items":["aaa","bbb"],
"name":"My Expense"
}]
GroupModel
类是:
class GroupModel {
var name: String? = null
var description: String? = null
var items: MutableList<String>? = null
constructor(name: String, description: String, items: MutableList<String>) {
this.name = name
this.description = description
this.items = items
}
}
并尝试以下代码会导致 Exception
:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
代码:
var model = gson.fromJson<Array<GroupModel>>(inputString, GroupModel::class.java)
最佳答案
[{
"description":"My expense to others",
"items":["aaa","bbb"],
"name":"My Expense"
},
{
"description":"My expense to others","
items":["aaa","bbb"],
"name":"My Expense"
}]
Kotlin 代码
val gson = GsonBuilder().create()
val Model= gson.fromJson(body,Array<GroupModel>::class.java).toList()
Gradle
implementation 'com.google.code.gson:gson:2.8.5'
关于Kotlin 使用 GSON 将 json 数组转换为模型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853750/