[英]Parsing Alamofire result into objects in Swift (using: Alamofire, SwiftyJSON & ObjectMapper)
I'm having problems parsing the incoming JSON. 我在解析传入的JSON时遇到问题。
This is my function: 这是我的功能:
func postCheckUserPhonenumbers(phonenumbers:[String], completionHandler: (([AnyObject?], AnyObject?) -> Void)) {
let urlString = Constant.apiUrl().stringByAppendingFormat(Constant.apiPostCheckUserPhonenumbers)
let phoneNumbersDictionary = phonenumbers.map({ ["number": $0] })
let JSON = try? NSJSONSerialization.dataWithJSONObject(phoneNumbersDictionary, options: [])
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = JSON
Alamofire.request(request).validate().responseJSON(completionHandler: {response in
if response.result.isSuccess{
if let value = response.result.value {
// let json = JSON(value)
if let users:Array<User> = Mapper<User>().mapArray(value) {
completionHandler(users, nil)
} else {
completionHandler([nil], nil)
}
}
}
if response.result.isFailure{
let message = ApiMessage()
message.message = "No users found"
completionHandler([nil],message)
}
})
}
Normally I cast the result into a JSON first but this time I get compile errors when trying to do that: 通常,我首先将结果转换为JSON,但这次尝试这样做时会出现编译错误:
It was indeed my JSON variable declared above the function. 实际上,这是我在函数上方声明的JSON变量。 I've now got this:
我现在有这个:
func postCheckUserPhonenumbers(phonenumbers:[String], completionHandler: (([AnyObject?], AnyObject?) -> Void)) {
let urlString = Constant.apiUrl().stringByAppendingFormat(Constant.apiPostCheckUserPhonenumbers)
let phoneNumbersDictionary = phonenumbers.map({ ["number": $0] })
let inputJSON = try? NSJSONSerialization.dataWithJSONObject(phoneNumbersDictionary, options: [])
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = inputJSON
Alamofire.request(request).validate().responseJSON(completionHandler: {response in
if response.result.isSuccess{
if let value = response.result.value {
let json = JSON(value)
let jsonString = json.rawString()
if let users:Array<User> = Mapper<User>().mapArray(jsonString) {
completionHandler(users, nil)
} else {
completionHandler([nil], nil)
}
}
}
if response.result.isFailure{
let message = ApiMessage()
message.message = "No users found"
completionHandler([nil],message)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.