Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json与Swift 2,提取数据_Json_Xcode_Swift2 - Fatal编程技术网

Json与Swift 2,提取数据

Json与Swift 2,提取数据,json,xcode,swift2,Json,Xcode,Swift2,我遇到了一个无法从JSON响应中访问值的问题 响应为:{“结果”:[true]} 当JSON用这个代码得到它时 do{ let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) let result:String = json["result"] pr

我遇到了一个无法从JSON响应中访问值的问题

响应为:{“结果”:[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有以下内容

是否仍然可以从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)")
        }

结果
不是
字符串
,它是
布尔的
数组
(用括号表示)

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

将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)")
}