在swift 4中使用Alamofire发出请求时,服务器的JSON解析错误

时间:2017-11-14 11:31:28

标签: json swift alamofire swift4

我需要向api发出post请求并从响应中获取数据。 api返回以下响应:

{
    valid: true
}

{
    valid: false
}

我的Alamofire请求看起来像这样:

parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, headers: headers).responseJSON{
    response in
    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //{ detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)"}
                    }

我似乎无法从服务器获取JSON数据以提取valid的值。相反,我收到错误:detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)" from the server

1 个答案:

答案 0 :(得分:1)

原来我在请求encoding: JSONEncoding.default中没有包含一个重要参数。(我猜订单很重要)以下是有效的:

parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
                .responseJSON{
                    response in
                    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //SUCCESS :{valid: 0}
                    }