我在从新版本的 Pokemon API 解析 JSON 数据时遇到问题,特别是“type”键中“name”的值。
Json 看起来像这样:
"types": [
{
"slot": 2,
"type": {
"name": "poison",
"url": "https://pokeapi.co/api/v2/type/4/"
}
},
{
"slot": 1,
"type": {
"name": "grass",
"url": "https://pokeapi.co/api/v2/type/12/"
}
}
],
"weight": 69
在 Alamofire 中解析后,我得到了下一个解决方案:
if let types = dict["types"] as? [Dictionary<String, String>] , types.count > 0 {
if let type = types[0]["type"] as? Dictionary<String, String> {
if let name = type["name"] {
self._type = name.capitalized
}
}
print("TypeAA: \(self._type)")
} else {
self._type = ""
}
并且这一行也没有被执行。 print("TypeAA: (self._type)") 请指教,如何正确解析并获取名为“type”的键中“name”的值?
最佳答案
你不能做 dict["types"] as? [Dictionary<String, String>]
因为 types
中的一项无法转换为 Dictionary<String, String>
. item
有像 "slot": 2
这样的整数和词典 "type": {...}
.所以它必须转换为 [String : Any]
第一的。
if let types = dict["types"] as? [Any], types.count > 0 {
if let firstObject = (types.first as? [String : Any]),
let type = firstObject["type"] as? [String : String],
let name = type["name"] {
self._type = name.capitalized
}
}
如果你想要每个项目的名称,你必须循环遍历 items
大批。
关于ios - 我如何解析这个 JSON Pokemon 字典? Sprite 宝可梦 API (swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464948/