如何使用 NSURLSession 在 Swift 中解析 JSON [英] How to parse JSON in Swift using NSURLSession

查看:22
本文介绍了如何使用 NSURLSession 在 Swift 中解析 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 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 中没有 try catch 时工作正常,但在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆