【问题标题】:Kotlin convert json array to model list using GSONKotlin 使用 GSON 将 json 数组转换为模型列表
【发布时间】:2018-02-18 16:11:11
【问题描述】:

我无法将 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:预期 BEGIN_OBJECT 但在第 1 行第 2 列路径 $

处为 BEGIN_ARRAY

代码:

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

【问题讨论】:

    标签: kotlin gson


    【解决方案1】:
    [{
      "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'
    

    【讨论】:

      【解决方案2】:

      我找到了一个实际在 Android 上使用 Kotlin 来解析给定类的 JSON 数组的解决方案。 @Aravindraj 的解决方案并不适合我。

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

      所以基本上,您只需要提供一个类(示例中为YourClass)和 JSON 字符串。 GSON 会解决剩下的问题。

      Gradle 依赖是:

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        猜你喜欢
        • 2018-05-29
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-07
        • 2021-11-07
        相关资源
        最近更新 更多