【发布时间】:2020-05-11 21:27:34
【问题描述】:
我有一个名为 villagers.json 的 JSON 文件,格式如下
[
{
"name": "Admiral",
"iconFilename": "brd06.png",
"houseFilename": "brd06_39_Admiral.png",
"species": "Bird",
"gender": "Male",
"personality": "Cranky",
"hobby": "Nature",
"birthday": "01/27",
"catchphrase": "aye aye",
"favoriteSong": "Steep Hill",
"filename": "brd06",
"uid": "B3RyfNEqwGmcccRC3",
"colors": [
"Black",
"Blue"
],
"styles": [
"Cool",
"Cool"
]
},
{ ... },
etc.
]
以下 sn-p 用于从 Android 资产中的 JSON 文件中读取 Villager POJO 列表。
// this works
fun getVillagersFromJSON(context: Context): List<Villager> {
val jsonFileString = getJsonDataFromAsset(context, "villagers.json")
return Gson().fromJson(jsonFileString, object : TypeToken<List<Villager>>() {}.type)
}
但是,当尝试使用以下两个函数来生成 POJO 的类型时,我收到了 com.google.gson.internal.LinkedTreeMap cannot be cast to Villager 错误。
fun getVillagersFromJSON(context: Context): List<Villager> {
val jsonFileString = getJsonDataFromAsset(context, "villagers.json")
jsonFileString?.let { return fromJson(it) }
return ArrayList()
}
// this use of type generics does NOT work
private inline fun <reified T> fromJson(json: String): List<T> {
return Gson().fromJson(json, object : TypeToken<List<T>>() {}.type)
}
使用 Kotlin、Gson 和类型泛型从 JSON 文件中读取 POJO 列表的正确方法是什么?
【问题讨论】:
-
可以显示json内容吗