gpt4 book ai didi

json - 无法从 AFNetworking 的 responseObject 解析 JSON

转载 作者:搜寻专家 更新时间:2023-10-30 21:53:05 27 4
gpt4 key购买 nike

我已阅读 this question并尝试在 Swift 中从 AFNetworking 的 responseObject 解析 JSON,但结果始终为 nil

这是我的代码的摘录:

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)
})

注意

var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // without "!" I will get EXC_BAD_INSTRUCTION at run time.

最佳答案

您可以将 responseObject 转换为字典

例如

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
})

附注从字典返回的值总是可选的

编辑:Xcode6 beta2 发布后,上面的代码不再有效。需要先将其转换为 AnyObject,然后再转换为字符串

let token : String? = (responseDict["token"] as AnyObject?) as? String

关于json - 无法从 AFNetworking 的 responseObject 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com