我无法将JSON数组转换为GroupModelarray.下面是我使用的JSON:

[{
  "description":"My expense to others",
  "items":["aaa","bbb"],
  "name":"My Expense"
 },
 {
  "description":"My expense to others","
  items":["aaa","bbb"],
  "name":"My Expense"
 }]

and the GroupModel class is:

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
    }
}

and trying the following code results in an Exception:

通用域名格式.谷歌.格森.JsonSyntaxException:java.lang.IllegalStateException:应为

代码:

var model = gson.fromJson<Array<GroupModel>>(inputString, GroupModel::class.java)

推荐答案

You need to use a TypeToken to capture the generic type of the array, and you need this to be the type that GSON sees as the target, instead of just GroupModel::class it is really a list of those. You can create a TypeToken and use it as follows:

Type groupListType = new TypeToken<ArrayList<GroupModel>>() {}.getType();
var model = gson.fromJson(inputString, groupListType);

Kotlin相关问答推荐

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

在Webflux应用程序中通过kotlin协程启动fire and forget job

如何在数据类中删除空格 (String)?

Kotlin 中的as Long和.toLong()有什么区别?

如何使用子变量在 Kotlin 中初始化父级

如果不为空,则为 builder 设置一个值 - Kotlin

如何从 kotlin 函数中 Select 正确的枚举值

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

Swift vs Kotlin 在排序数组上的表现

如何使 TextInputEditText 只读?

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

如何在MVVM架构中观察RecyclerView适配器中的LiveData?

有没有办法在数据类构建时转换属性的值?

Kotlin:sealed class cannot "contain" data classes?

Kotlin中的下划线名称是为什么保留的?

Jacoco在Gradle 7.0.2和Kotlin 1.5.10上失败

如何获取Kotlin中变量的名称?

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

用 kotlin 学习 Android MVVM 架构组件

为什么在 Kotlin 中return可以返回一个return?