如何使用NSURLSession在Swift中解析JSON [英] How to parse JSON in Swift using NSURLSession
问题描述
我正在尝试解析JSON,但收到此错误:
I am trying to parse JSON but getting this error:
表达类型含糊不清,没有更多上下文
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中没有尝试捕获就可以正常工作,但是在Xcode 7中却无法工作.
This is working fine with out try catch in Xcode 6.4 but this is not working in Xcode 7.
推荐答案
不要为解码对象声明AnyObject
类型,因为您希望它成为NSDictionary
,并且您正在执行转换以执行此操作
Don't declare an AnyObject
type for your decoded object since you want it to be an NSDictionary
and you're performing a conversion to do this.
此外,最好将零选项用于NSJSONSerialization,而不要使用随机选项.
Also it's better to use zero options for NSJSONSerialization instead of random ones.
在我的示例中,我还使用了一个自定义错误类型来进行演示.
In my example I've also used a custom error type just for demonstration.
请注意,如果您使用的是自定义错误类型,则还必须包含通用的catch
才能详尽无遗(在此示例中,只需简单地向下转换为NSError).
Note, if you're using a custom error type, you have to also include a generic catch
to be exhaustive (in this example, with a simple downcasting to 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()
}
这篇关于如何使用NSURLSession在Swift中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!