Kotlin使用GSON将json数组转换为模型列表 [英] Kotlin convert json array to model list using GSON

查看:995
本文介绍了Kotlin使用GSON将json数组转换为模型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am not able to convert a JSON Array into a GroupModel array. Below is the JSON I used:

[{
  "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:

and trying the following code results in an Exception:

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期 BEGIN_OBJECT,但在第1行第2列路径$

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)

推荐答案

您需要使用TypeToken来捕获数组的通用类型,并且需要将其作为GSON视为目标的类型.只是GroupModel::class的确是这些列表.您可以创建一个TypeToken并按以下方式使用它:

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使用GSON将json数组转换为模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆