ios - 我如何解析这个 JSON Pokemon 字典? Sprite 宝可梦 API (swift 3)

标签 ios json swift parsing

我在从新版本的 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/

相关文章:

ios - 框架不分配约束

ios - iPhone 应用程序使用什么 dpi 分辨率?

ruby-on-rails - 使用 JSON 和 POST 将我的 iOS 应用程序连接到 Web 应用程序问题

javascript - 'foo$bar'之类的键时如何访问json对象值

ios - 如何设置重复本地通知的开始和结束时间?

ios - CoreData导入重载内存

ios - 删除部分 CGPath

javascript - 从 webview 打开应用商店?

iphone - 崩溃日志链接到哪个 .dSYM

Android:如何显示JSON Post结果