【发布时间】:2018-11-25 05:36:15
【问题描述】:
我在解析来自新版 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”的值?
【问题讨论】:
-
使用Decodable比手动解析响应要容易得多。
-
感谢@Kamran,但请就这些代码提出建议。