[英]Validate JSON response with Alamofire
Is it possible to have a Alamofire validator that gets the parsed JSON response, check a property and return true / false depending on that value? 是否有可能使用Alamofire验证程序来获取已解析的JSON响应,检查属性并根据该值返回true / false?
I have an API that always returns 200 response codes, but the response has a success property. 我有一个始终返回200个响应代码的API,但是响应具有成功属性。
I would like to check this property before the responseJSON callback is fired and only call responseJSON if success == true. 我想在触发responseJSON回调之前检查此属性,并且仅在成功== true时才调用responseJSON。
Is this possible with custom validators? 使用自定义验证程序可以做到这一点吗?
Found a solution I feel ok with. 找到了可以接受的解决方案。 First I created extension methods that check for errors and extract the data I'm interested in. I have one success callback and one error callback. 首先,我创建了扩展方法来检查错误并提取我感兴趣的数据。我有一个成功回调和一个错误回调。
import Foundation
import Alamofire
extension Request {
public func apiSuccess(
queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: [String:AnyObject] -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: { response in
if let jsonValue = response.result.value as? [String:AnyObject] {
let success = jsonValue["success"] as! Bool
if (success) {
completionHandler(jsonValue["object"] as! [String:AnyObject])
}
}
}
)
}
public func apiError(
queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: [String] -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: { response in
if let jsonValue = response.result.value as? [String:AnyObject] {
let success = jsonValue["success"] as! Bool
if (!success) {
let errorDict = jsonValue["errors"] as! [String:[String]]
var errors : [String] = []
errorDict.keys.forEach { key in
errors += errorDict[key] as [String]!
}
completionHandler(errors)
}
}
}
)
}
}
Then I can use it like this: 然后我可以像这样使用它:
Alamofire.request(.POST, url,
parameters: parameters,
encoding: .JSON)
.apiSuccess { response in
print("Success Callback", response)
}
.apiError { errors in
print("Errors ", errors)
}
I don't think it is. 我认为不是。 Validator blocks don't receive the response data as arguments, only headers and such. 验证程序块不接收响应数据作为参数,仅接收标头等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.