美文网首页
swift解析json

swift解析json

作者: 喵喵粉 | 来源:发表于2020-02-20 15:17 被阅读0次

    用到第三方库 SwiftyJSON

    func testDemo() {
        let jsonStr = "[{\"name\": \"hangge\", \"age\": 100, \"phones\": [{\"name\": \"公司\",\"number\": \"123456\"}, {\"name\": \"家庭\",\"number\": \"001\"}]}, {\"name\": \"big boss\",\"age\": 1,\"phones\": [{ \"name\": \"公司\",\"number\": \"111111\"}]}]"
        
        if let jsonData = jsonStr.data(using: .utf8, allowLossyConversion: false) {
            ///使用JSONSerialization
            let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [[String: Any]]
            if array != nil, array!.count > 0 {
                if let in1:[String:Any] = array![0] {
                    if let phones = in1["phones"] as? [[String: Any]] {
                        let phone = phones.first
                        if let nub = phone?["number"] as? String {
                            DebugLog(nub)
                        }
                    }
                }
            }
            
            ///使用SwiftyJSON https://blog.csdn.net/ly410726/article/details/80235007
            do {
                let json = try JSON(data: jsonData)
                if let name = json[0]["phones"][10]["name"].string {
                    DebugLog(name)
                }
                if let dic = json[0]["phones"][0].dictionary {
                    DebugLog(dic)
                    DebugLog(dic["number"])
                }
                 
            } catch  {
                DebugLog("SwiftyJSON catch:\(error.localizedDescription)")
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:swift解析json

          本文链接:https://www.haomeiwen.com/subject/uhuxqhtx.html