【问题标题】:Swift 2.0 String of JSON to JSONSwift 2.0 JSON 到 JSON 的字符串
【发布时间】:2015-07-02 01:50:54
【问题描述】:

我正在使用 Swift 2.0 并正在努力处理 JSON。我以Swift.Optional<NSData> 的形式从网站中提取JSON。我可以使用

将其转换为字符串
if let x = NSString(data: data!, encoding: NSUTF8StringEncoding){
  let y = x as String
}

我正在努力快速地将这些 JSON 数据放入字典中。最好的方法是什么?

更新

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    if let z = NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [NSObject: AnyObject] {
    }

它出错了

  • 没有更多上下文,表达式类型不明确
  • 调用可以抛出,但它没有标记'try'并且错误没有处理

【问题讨论】:

    标签: json swift swift2


    【解决方案1】:

    在 Swift 2 中,如果一个函数“抛出”(如 NSJSONSerialization 那样),您必须在 do ... catch 块内处理函数调用,并在抛出函数之前使用 try,如下所示:

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        do {
            let z = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [NSObject: AnyObject]
            print(z)
        } catch let myJSONError {
            print(myJSONError)
        }
    }
    
    task!.resume()
    

    请注意,在本例中,do...catchtry 处理了可能的 NSJSONSerialization 故障,并带有自定义 myJSONError 错误,但未处理 NSURLSession 可能的故障:您仍然必须检查 error 变量才能处理此问题。这是因为NSJSONSerialization“抛出”但NSURLSession没有。

    【讨论】:

    • 错误:表达式类型不明确,没有更多上下文 [let z = ...]
    • 看看我的screenshot,我的例子没有错误。您得到的错误与 JSON 解码无关。尝试更改变量的名称以使编译器满意,他不喜欢您的z。 :) 您可能会因为代码中的其他变量或函数而得到这个,其他地方。
    【解决方案2】:

    您不需要将其转换为字符串。你可以这样做:

    if let JSONDict = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject: AnyObject] 
    {
        // Do stuff with the JSONDict which is a Swift dictionary.
        // For example: let some = JSONDict["key"] as? ValueType will allow you to access the key of the JSONDict
    }
    

    如果您使用的是 Swift 2,则需要使用 do try and catch 来检查错误。这是完整的代码,包括检查 nil 的可选项和处理不良连接错误、404 错误等。还可以确保 URL 有效。使用新的保护语句来减少缩进:

        guard let task = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
        guard let data = data, error == nil 
        else 
        {
            // Checks for errors if the task fails like for bad connectivity.
            print(error);
            return;
        }
        do 
        {
            guard let JSONDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject: AnyObject] 
            else
            {
                // The JSONDict wasn't a dictionary. Maybe its an array here? If it is change the structure of the parsing.
                return
            }
            // Do stuff with the JSONDict which is a Swift dictionary.
            // For example: let some = JSONDict["key"] as? ValueType will allow you to access the key of the JSONDict
        }
        catch error 
        { 
            // JSON parsing error. 
            print(error) 
        }
    }
    else 
    { 
        // Error task wasn't created that's unusual unless the URL was bad.
        // Fail here so that you can trace the stack and debug.
        assertionFailure();
    }
    task.resume()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 1970-01-01
      • 2012-08-07
      • 2018-09-08
      • 1970-01-01
      相关资源
      最近更新 更多