Json 和 Swift 2、提取数据

Json with Swift 2, extracting data

我遇到了无法从 JSON 响应访问值的问题,

响应是:{"result":[true]}

当 JSON 使用此代码获取它时

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)


                let result:String = json["result"]

                   print(result)


            }catch {
                print("Error with Json: \(error)")
            }

我得到一个错误,当我进行调试时,我看到 json 有以下内容

how json is stored

是否可以访问 json 的结果?将其视为数组或字典都不起作用

有什么想法吗?

谢谢

这样试试

do{

            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as! NSDictionary
            let result = json["result"] as! NSArray
               print(result)

            let boole = result[0];

        }catch {
            print("Error with Json: \(error)")
        }

result 不是 String,它是 BoolArray(用括号表示)。

基本上不要注释类型,除非编译器需要它们。

将 JSON 转换为正确的类型并使用 Swift 本机集合类型。还建议使用可选绑定以避免意外崩溃。

do {
     if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [String:AnyObject],
          result = json["result"] as? [Bool] where !result.isEmpty {
        print(result[0])
     }

} catch {
     print("Error with Json: \(error)")
}