Swift - 无法从NSData创建JSON对象

时间:2014-10-31 02:20:04

标签: ios json swift nsdata

我正在向服务器发出发布请求以验证登录尝试。如果尝试有效,则会在NSdata块中从服务器返回一些信息。我希望能够将其分解为 json 对象,以便我可以轻松解析它。

func connectToServerAndGetCookie(username: String, password: String) -> NSString {
    var url = "********"
    var request = HTTPTask()
    var parameters = ["username": username, "password": password]
    var cookies = ""
    request.requestSerializer = JSONRequestSerializer()
    request.POST(url, parameters: parameters, success: {(response: HTTPResponse) in
        if response.responseObject != nil {
            let data = response.responseObject as NSData
            var jsonError: NSError?
            let str = NSString(data: data, encoding: NSUTF8StringEncoding)

 ////////////////// here is where it fails on the nsjsonserialization. the error: 
//////////////////Cannot convert the expression's type 'NSDictionary?' to type 'NilLiteralConvertible'
// but when i remove the ? on the as, I get the error: expression does not conform to type '$T5'

let json2 : NSDictionary = NSJSONSerialization.JSONObjectWithData(str, options: nil, error:&jsonError ) as? NSDictionary

            println(json2)
            // parse cookies here
        }
        },failure: {(error: NSError) in
            println(" error \(error)")
    })
    return cookies
}

我只是想将NSData块分解为json对象

2 个答案:

答案 0 :(得分:5)

您可以按原样使用NSData,而不是将NSData转换为String。

import Foundation

var error: NSError?
let jsonData: NSData = response.responseObject

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

答案 1 :(得分:1)

对于swift 3,您也可以尝试:

let jsonData: Data = data
let jsonDict = try! JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary

例如:

print(jsonDict["width"])