【问题标题】:Get string from JSON Array in Swift从 Swift 中的 JSON 数组中获取字符串
【发布时间】:2016-12-20 12:14:29
【问题描述】:

我需要从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

谁能帮我把这个字符串取出来?我无法找出我在这里所做的错误。任何帮助,将不胜感激。

【问题讨论】:

  • 它不是一个数组,它是一个字典。
  • 试试这个var info : NSDictionary = dictionary.valueForKey("data") as NSDictionary var names: String? = info["firstName"] as? String println("name ++\(names)")
  • 如果出现任何问题请告诉我谢谢!
  • @MuseerAnsari 谢谢。它正在工作,但使用“可选”打印。您能否将此添加为答案,以便我接受。
  • 是的,只需复制并粘贴我的答案(如下所示)我已更新,如果工作正常,请点赞,谢谢!

标签: arrays json swift


【解决方案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!)")

}

【讨论】:

    【解决方案2】:
    let dataId = response.value(forKeyPath: "data.id") as! NSNumber
    

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

    【讨论】:

    • 感谢您的支持。
    【解决方案3】:

    试试这个:

    do
    {
     let data = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
    }
    catch _{}
    
    let data      = json["data"] as! NSDictionary
    let firstName = data["firstName"]
    

    【讨论】:

    • 感谢您的支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2020-11-06
    相关资源
    最近更新 更多