【问题标题】:parse json using swift2 and error with NSJSONReadingOptions使用 swift2 解析 json 并使用 NSJSONReadingOptions 出错
【发布时间】:2015-10-18 18:11:49
【问题描述】:

我正在尝试从我正在使用的网络服务器解析 json,尽管我可以返回 iOS 8,但我实际上无法做到这一点。这是我正在使用的代码:

let str = "URL-THAT-HAS-THE-JSON"

let url = NSURL(string: str)

let data = NSData(contentsOfURL: url!)

var names : [String] = []
do
{
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [] )
    if let blogs = json["blogs"] as? [[String: AnyObject]]
    {
        for blog in blogs
        {
            if let name = blog["name"] as? String
            {
                names.append(name)
            }
        }
    }
}
catch {
    print("error serializing JSON: \(error)")
}
print (names)

不幸的是,我不能给你带有 json 的 url,但我可以确保它在服务器端工作。有人可以帮我解决我做错了什么吗?

【问题讨论】:

  • options: nil 应该是 options: [],如(例如)stackoverflow.com/questions/30769387/… 和一些类似的问题。
  • 好的,我只是这样做并从 nil 切换到 [ ] 但这似乎并不能解决问题,因为我仍然在该行中收到 EXC_BAD_INSTRUCTION 错误。有什么想法有什么问题吗?
  • 你正在强制解开data。是nil吗?
  • 您所说的“仍在获得”是什么意思?您的原始代码根本没有编译,因此它不会在运行时崩溃。除了“我实际上无法管理”之外,您也没有描述问题中的问题。
  • 是的数据是 nil,所以我明确地解开一个 nil 值,因此我的应用程序崩溃了。谢谢

标签: ios json swift swift2


【解决方案1】:

问题的答案是,我正在解包值为 nil 的数据,导致我的应用程序崩溃。谢谢大家的回答。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多