如何使用NSURLSession在Swift中解析JSON

Vip*_*617 13 json swift

我试图解析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()
}
Run Code Online (Sandbox Code Playgroud)

这在Xcode 6.4中使用try catch工作正常,但这在Xcode 7中不起作用.

aya*_*aio 33

不要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()
}
Run Code Online (Sandbox Code Playgroud)

与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()
}
Run Code Online (Sandbox Code Playgroud)