从Swift中的JSON Array获取字符串

时间:2016-12-20 12:14:30

标签: arrays json swift

我需要从JSON Array获取字符串,这是来自外部服务器的响应。这是我的代码:

if let dictionary = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers,error: &parsingError) as NSDictionary?{

    var info : NSArray = dictionary.valueForKey("data") as NSArray
    var names: String? = info[0].valueForKey("firstname") as? String

    println("name ++\(names)")

}

它正在编译但是当我执行时,没有运行我得到了

  

主题8:exc_bad_access(code = 2 ..

这是来自服务器端的Dictonary

{
 data =     {
     Id = 55;
     firstName = fgg;
     gender = 1;
 };
 success = 1; }

我跟踪线程没有成功:Getting Values from JSON Array in Swift

任何人都可以帮我把这个字符串拿出来吗?我无法找到我在这里所做的错误。任何帮助,将不胜感激。

3 个答案:

答案 0 :(得分:1)

试试这个

if let dictionary = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers,error: &parsingError) as NSDictionary?{

    var info : NSDictionary = dictionary.valueForKey("data") as! NSDictionary 
    var names: String? = info["firstName"] as? String 
    println("name ++\(names!)")

}

答案 1 :(得分:0)

let dataId = response.value(forKeyPath: "data.id") as! NSNumber

如果不进行反序列化,我通常会这样做。

答案 2 :(得分:0)

试试这个:

do
{
 let data = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
}
catch _{}

let data      = json["data"] as! NSDictionary
let firstName = data["firstName"]