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