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

时间:2018-02-18 16:11:12

标签: 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但在第1行第2列路径$

处是BEGIN_ARRAY

代码:

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

3 个答案:

答案 0 :(得分:3)

您需要使用TypeToken来捕获数组的泛型类型,并且您需要将其作为GSON视为目标的类型,而不仅仅是GroupModel::class它实际上是一个列表那些。您可以创建TypeToken并按如下方式使用它:

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

答案 1 :(得分:2)

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

科林代码

val gson = GsonBuilder().create()
val Model= gson.fromJson(body,Array<GroupModel>::class.java).toList()

成绩

implementation 'com.google.code.gson:gson:2.8.5'

答案 2 :(得分:0)

我找到了一个实际上可以在Android上与Kotlin一起使用的解决方案,用于解析给定类的JSON数组。 @Aravindraj的解决方案对我而言并不奏效。

val fileData = "your_json_string"
val gson = GsonBuilder().setPrettyPrinting().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()

因此,基本上,您只需要提供一个类(示例中为YourClass)和JSON字符串即可。 GSON会解决其余的问题。

相关问题