本文介绍了无法从AFNetworking的responseObject解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已阅读此问题,并尝试解析来自Swift中AFNetworking的responseObject的JSON,但结果始终为nil
.
I have read this question and trying to parse JSON from AFNetworking's responseObject in Swift but the result is always nil
.
以下是我的代码的摘录:
Here is excerpt from my code:
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFJSONResponseSerializer()
manager.requestSerializer.setAuthorizationHeaderFieldWithUsername(username, password: password)
manager.POST("endpoint-that-respond-token-in-json",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println(responseObject.description) // { token = "bd8f26da-219a-4a88-be80-b09207dfc067"; }
var x: NSString = responseObject.description
var error: NSError?
var data = x.JSONString().dataUsingEncoding(NSUTF8StringEncoding)
println(data) // <227b5c6e 20202020 746f6b65 6e203d20 5c226539 35613462 36642d38 6361612d 34343537 2d623937 612d3330 63613236 62316338 34315c22 3b5c6e7d 22>
var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString) // "{\n token = \"e95a4b6d-8caa-4457-b97a-30ca26b1c841\";\n}"
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary!
println(json) // nil
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
println(error)
})
N.B.
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // without "!" I will get EXC_BAD_INSTRUCTION at run time.
推荐答案
您可以将responseObject转换为字典
You can cast the responseObject to dictionary
例如
manager.POST("endpoint-that-respond-token-in-json",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println(responseObject.description) // { token = "bd8f26da-219a-4a88-be80-b09207dfc067"; }
let responseDict = response as Dictionary<String, AnyObject>
var token = responseDict["token"] as String!
println(token)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
})
p.s.从字典返回的值始终是可选的
p.s. the value return from dictionary always be optional
Xcode6 beta2发布后,以上代码不再起作用.需要先将其强制转换为AnyObject,然后强制转换为字符串
After Xcode6 beta2 release, above code doest not work anymore. Need to cast it to AnyObject first then cast to string
let token : String? = (responseDict["token"] as AnyObject?) as? String
这篇关于无法从AFNetworking的responseObject解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!