使用Swift 2进行NSJSONSerialization

时间:2015-09-30 13:01:40

标签: json swift2

import UIKit

let url = NSURL(string: "http://example.com/test.php")
let request = NSMutableURLRequest(URL: url!)

// modify the request as necessary, if necessary

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if data == nil {
        print("request failed \(error)")
        return
    }

    var parseError: NSError?
    if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as? [String: String] {
        if let name = json["name"] {
            print("name = \(name)")   // if everything is good, you'll see "William"
        }
    } else {
        print("parsing error: \(parseError)")
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("raw response: \(responseString)")
    }
}
task.resume()

此代码在更新Xcode 7之前有效,但现在

出现错误
if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as? [String: String] {

任何人都可以帮我转换为Swift 2吗?

1 个答案:

答案 0 :(得分:1)

你去吧

let url = NSURL(string: "http://example.com/test.php")
    let request = NSMutableURLRequest(URL: url!)

    // modify the request as necessary, if necessary

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if data == nil {
            print("request failed \(error)")
            return
        }

        do{
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {
                if let name = json["name"] {
                    print("name = \(name)")   // if everything is good, you'll see "William"
                }
            } else {
                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("raw response: \(responseString)")
            }
        }catch {
            print("bom bom bom error")
        }

    }
    task.resume()