Gson 反序列化 json 响应期间类型不匹配与 kotlin

Type mismatch during Gson deserialize json response with kotlin

我正在尝试序列化下面的 json 响应,但我不确定该怎么做。

这是 Json 我的后端 returns:

[
  {
    "title": "Dummy section, should not be seen",
    "type": "dummy_test",
    "metadata": []
  },
    {
    "title": "Title1",
    "type": "categories_products",
    "metadata": [
      {
        "id": "1272"
      }
    ]
  },
  {
    "title": "Title2",
    "type": "categories_products",
    "metadata": [
      {
        "id": "996"
      }
    ]
  }
]

这是我的 ExploreItem class:

data class ExploreItem(
    @SerializedName("metadata") val metadata: List<Metadata> = listOf(),
    @SerializedName("title") val title: String = "",
    @SerializedName("type") val type: String = ""
) {
    enum class ExploreItemType(val value: String) {
        @SerializedName("unknown")
        UNKNOWN("unknown"),

        @SerializedName("other_companies")
        OTHER_COMPANIES("other_companies"),

        @SerializedName("categories_products")
        CATEGORIES_PRODUCTS("categories_products"),

        @SerializedName("popular_categories")
        POPULAR_CATEGORIES("popular_categories")
    }
}

data class Metadata(
    @SerializedName("id") val id: String = ""
)

现在我正尝试像这样在存储库中序列化它:


Serializer.defaultJsonParser.fromJson(response.body!!.string(),ExploreItem::class.java )

但它不起作用,因为它需要一个 ExploreItem 列表。如何重写序列化程序表达式以将其解析为列表?

来自你的错误

Type mismatch. Required:List Found:ExploreItem!

Post 错误非常重要,Gson 告诉你它想要一个 List 而不是 ExploreItem.

的对象

换句话说,您是通过调用 Serializer.defaultJsonParser.fromJson(response.body!!.string(),ExploreItem::class.java )

告诉 Gson

“嘿 Gson,从字符串中我想要一个对象 ExploreItem”,Gson 告诉你“嘿我的朋友,你的字符串以 [ ] 开头肯定是一个列表而不是单个对象。"

你需要传入Serializer.defaultJsonParser.fromJson(response.body!!.string(),List<ExploreItem>::class.java)

P.s:我不确定 Kotlin 语法