我正在尝试解析 JSON 但出现此错误:
type of expression is ambiguous without more context
我的代码是:
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 中没有 try catch 时工作正常,但在 Xcode 7 中不起作用。
最佳答案
不要为你的解码对象声明一个 AnyObject
类型,因为你希望它是一个 NSDictionary
并且你正在执行一个转换来做到这一点。
此外,最好为 NSJSONSerialization 使用零选项而不是随机选项。
在我的示例中,我还使用了一个自定义错误类型来进行演示。
请注意,如果您使用的是自定义错误类型,则还必须包括一个通用的 catch
以便详尽无遗(在本例中,通过简单向下转换为 NSError)。
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()
}
关于json - 如何使用 NSURLSession 在 Swift 中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805045/