Gson FromJson返回null,我错过了什么?

57hvy0tb  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(141)

我尝试使用gson fromJson,但每次都得到这个print => Countries(countries=null)。我错过了什么?
//代码

data class Countries(val countries: Map<String, List<String>>)

val jsonString = """
    {
      "Afghanistan": [
        "Herat",
        "Kabul",
        "Kandahar",
        "Molah",
        "Rana",
        "Shar",
        "Sharif",
        "Wazir Akbar Khan"
      ],
      "Albania": [
        "Elbasan",
        "Petran",
        "Pogradec",
        "Shkoder",
        "Tirana",
        "Ura Vajgurore"
      ]
    }
""".trimIndent()

        val countries = Gson().fromJson(jsonString, Countries::class.java)
        println(countries)
zbdgwd5y

zbdgwd5y1#

确定类型

val countryCityType = object : TypeToken<Map<String, List<String>>>() {}.type

GSON解析

val countryCityData: Map<String, List<String>> = Gson().fromJson(jsonString, countryCityType)

println(countryCityData)
byqmnocz

byqmnocz2#

找不到countries键。这里基本上有三种选择。
1.你可以修改json本身:

val jsonString = """
{
  "countries": {
    "Afghanistan": [
      "Herat",
      "Kabul",
      "Kandahar",
      "Molah",
      "Rana",
      "Shar",
      "Sharif",
      "Wazir Akbar Khan"
    ],
    "Albania": [
      "Elbasan",
      "Petran",
      "Pogradec",
      "Shkoder",
      "Tirana",
      "Ura Vajgurore"
    ]
  }
}
""".trimIndent()

1.或者,您可以更改您要实体化的实体(例如,使用object : TypeToken<Map<String, List<String>>>() {}.type作为第二个参数)。
1.另一种选择是为现有的json和Countries类创建一个自定义编译器,如下所示:

val countriesDeserializer =
    JsonDeserializer { json, _, context ->
        Countries(
            context.deserialize(json, object : TypeToken<Map<String, List<String>>>() {}.type)
        )
    }

使用GsonBuilder().registerTypeAdapter(Countries::class.java, countriesDeserializer).create()而不是简单的Gson()

相关问题