将Alamofire解析为Swift中的对象(使用:Alamofire,SwiftyJSON& ObjectMapper)

时间:2016-10-04 01:39:09

标签: ios json swift alamofire swifty-json

我在解析传入的JSON时遇到问题。

这是我的功能:

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

enter image description here

通常我先将结果转换为JSON,但这次尝试执行此操作时出现编译错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

确实是我在函数上面声明的JSON变量。我现在得到了这个:

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