在Swift中从JSON数组获取字符串

时间:2023-02-06 00:00:51

I need to get string from the JSON Array which is a response from the external server. This is my code:

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

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

}

It's compiling but when I execute, not running I got as

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

thread 8:exc_bad_access (code=2 ..

线程8:exc_bad_access(代码= 2 . .

This is Dictonary coming from server side

这是来自服务器端的二项式

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

I followed thread without success : Getting Values from JSON Array in Swift

我跟随线程,但没有成功:在Swift中从JSON数组获取值

Can anyone help me to get this string out? I cannot find out the error I have done here. Any help would be appreciated.

谁能帮我把这根绳子弄出来吗?我找不到我在这里犯的错误。如有任何帮助,我们将不胜感激。

3 个解决方案

#1


1  

Try this

试试这个

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!)")

}

#2


0  

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

I usually do this if am not up to deserialization.

如果不是反序列化的话,我通常会这样做。

#3


0  

Try this :

试试这个:

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

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

#1


1  

Try this

试试这个

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!)")

}

#2


0  

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

I usually do this if am not up to deserialization.

如果不是反序列化的话,我通常会这样做。

#3


0  

Try this :

试试这个:

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

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