我正在尝试解析JSON但收到此错误:
在没有更多上下文的情况下,表达类型不明确
我的代码是:
func jsonParser() { let urlPath = "http://headers.jsontest.com/" let endpoint = NSURL(string: urlPath) let request = NSMutableURLRequest(URL:endpoint!) let session = NSURLSession.sharedSession() NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) throws -> Void in if error != nil { print("Get Error") }else{ //var error:NSError? do { let json:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary print(json) } catch let error as NSError { // error handling print(error?.localizedDescription) } } } //task.resume() }
在没有尝试捕获的情况下,在Xcode 6.4中可以正常工作,但是在Xcode 7中则无法工作。
不要AnyObject为已解码对象声明类型,因为您希望它是an,NSDictionary并且您正在执行转换来做到这一点。
AnyObject
NSDictionary
另外,最好将零选项用于NSJSONSerialization而不是随机选项。
在我的示例中,我还使用了一个自定义错误类型来进行演示。
请注意,如果您使用的是自定义错误类型,则还必须包括泛型,catch以使其详尽无遗(在本示例中,将简单向下转换为NSError)。
catch
enum JSONError: String, ErrorType { case NoData = "ERROR: no data" case ConversionFailed = "ERROR: conversion from JSON failed" } func jsonParser() { let urlPath = "http://headers.jsontest.com/" guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint") return } let request = NSMutableURLRequest(URL:endpoint) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in do { guard let data = data else { throw JSONError.NoData } guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else { throw JSONError.ConversionFailed } print(json) } catch let error as JSONError { print(error.rawValue) } catch let error as NSError { print(error.debugDescription) } }.resume() }
与Swift 3.0.2相同:
enum JSONError: String, Error { case NoData = "ERROR: no data" case ConversionFailed = "ERROR: conversion from JSON failed" } func jsonParser() { let urlPath = "http://headers.jsontest.com/" guard let endpoint = URL(string: urlPath) else { print("Error creating endpoint") return } URLSession.shared.dataTask(with: endpoint) { (data, response, error) in do { guard let data = data else { throw JSONError.NoData } guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else { throw JSONError.ConversionFailed } print(json) } catch let error as JSONError { print(error.rawValue) } catch let error as NSError { print(error.debugDescription) } }.resume() }