Kotlin 使用 GSON 将 json 数组转换为模型列表

标签 kotlin gson

我无法将 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/

相关文章:

android - 使用 Gradle 3.1.2 无法解决 Retrofit

android - Firestore 查询 StartAt(DocumentReference) 没有给出正确的结果

java - Gson按值对TreeMap的ArrayList进行排序

java - 将嵌套的 json 数据解析为字符串

java - A 类声明了多个 JSON 字段

android - 如何使用 Retrofit/Gson 反序列化 JSON 中相同类型但字段名称不同的对象列表?

java - 在每个“回收者” View 中添加自定义布局的问题

kotlin - 当其他成员可以访问时,为什么不能访问 Kotlin 伴生对象内的对象 "statically"?

kotlin - 使用readLine通过用户输入搜索列表

android - Gradle ExoPlayer和GSON