无法在Kotlin中使用TypeToken +泛型和Gson处理json树列表

时间:2018-07-29 03:39:19

标签: json kotlin android gson

我有如下的json结构:

:car2

这是我的Gson数据类映射:

{
  "object": "list",
  "total": 3,
  "data": [
    {
      "object": "brand",
      "id": "15243937043340",
      "company": {
        "object": "company",
        "id": "956936000",
        "name": "ABC"
      },
      "name": "Kindle",
      "images": [
        "http://www.spacecentrestorage.com/assets/uploads/General/SCS-Slide02-Commercial.jpg"
      ]
    },
    {
      "object": "brand",
      "id": "15243937043340",
      "company": {
        "object": "company",
        "id": "956936000",
        "name": "ABC"
      },
      "name": "Kindle",
      "images": [
        "http://www.spacecentrestorage.com/assets/uploads/General/SCS-Slide02-Commercial.jpg"
      ]
    },
    {
     "object": "brand",
      "id": "15243937043340",
      "company": {
        "object": "company",
        "id": "956936000",
        "name": "ABC"
      },
      "name": "Kindle",
      "images": [
        "http://www.spacecentrestorage.com/assets/uploads/General/SCS-Slide02-Commercial.jpg"
      ]
    }
  ],
  "associated": {}
}

当要像上面那样提取树时,我发现返回的数据字符串变为Malformed Json并在$ [0] .companies.null上给出MalformedJsonException

我已阅读过recursive deserialisation function,但在我的情况下它不起作用。我采用以下方法反序列化,使用原始方法,会导致错误

data class Response (

        @SerializedName("object")
        val obj: String,
         val total: Int,
         val data: List<*>,
         val associated: Response
)


data class Brand (

        @SerializedName("object")
        val obj: String,
        val id: String,
         val name: String,
         val images: List<String>,
         val company: Company
)

   data class Company (

        @SerializedName("object")
        val obj: String,
        val id: String,
         val name: String 
)

我想问:

  1. 如果将json组件返回到字符串,是否应删除所有缩进和符号?

  2. 要提取对象列表中元素的所有关联对象,使用Gson反序列化对象列表时需要采取什么预防措施?

1 个答案:

答案 0 :(得分:0)

如果将dataResponse列表的类型参数设置为Brand,GSON会知道如何反序列化列表中的项目。

data class Response (

    @SerializedName("object")
    val obj: String,
    val total: Int,
    val data: List<Brand>, 
    val associated: Response

)

使用此方法,无需再次解析列表中的项目,您可以像这样获得所有brands

val response = Gson().fromJson(queryResult , Response::class.java)
val dataList = response.data
print("brands: " )
dataList.forEach { println(it) }