带有JSONEncoding的Alamofire请求给出了错误

时间:2018-11-09 05:08:27

标签: ios swift alamofire

在Alamofire.request中将JSON对象作为参数传递时出现错误

func apiCall2(anyBaseUrl: String = "", apiFunction: ApiName, method m: HTTPMethod = .get,
             parameters: [String: Any]? = nil, isJsonEncoding: Bool = false,
             completion:  @escaping (Bool, Any?, Error?) -> Void) {

    var requestUrl = "\(ActiveBaseURL())\(apiFunction.rawValue)"

    if anyBaseUrl != "" {
        requestUrl = "\(anyBaseUrl)\(apiFunction.rawValue)"
    }

    var param = [String: Any]()

    if let p = parameters {
        param = p
    }

    Alamofire.request(requestUrl, method: m, parameters: param, encoding: isJsonEncoding ? JSONEncoding.default: URLEncoding.default)
        .authenticate(user: ApiUserName, password: ApiPassword)
        .responseJSON(options: .allowFragments) { response in
            print("request body: \(response.request?.httpBody)")
            if response.result.isSuccess {
            }
            print(response.result.error?.localizedDescription)
            completion(false, nil, response.result.error)
    }
}

我的实际JSON格式是

  

{“ discount_code”:“”,“ giftcard_code”:“”,“ dt”:   “ 2018-11-15”,“发货”:{       “ state”:“ sel”,       “ name”:“ Test”,       “ address1”:“ testevhsd”,       “ city”:“测试城市”,       “ address2”:“ testfhd”,       “ mobile”:“ 89464633”,       “ shipment_code”:“是”,       “ postal”:“ 672673”,       “ country_id”:“ 129”},“ iccid”:“”,“ uid”:“ 3592”,“ product”:[       {         “ id”:104,         “ type”:“ countryPlan”,         “数量”:1       }]}

这就是我在函数中传递JSON的方式

var parms: Parameters {

        return  [
            "uid": "3592",
            "product": [
                ["id": 104,"type":"countryPlan", "qty": 1]
            ],
            "shipping": ["name":"Test", "mobile": "89464633", "address1": "testevhsd",
                         "address2": "testfhd", "city": "test city", "state": "sel",
                         "postal": "672673", "shipment_code": "YES", "country_id": "129"],
            "discount_code": "",
            "dt":"2018-11-15",
            "giftcard_code": "",
            "iccid": ""]
    }

    Service.shared.apiCall2(apiFunction: .CheckOut, method: .post, parameters: parms, isJsonEncoding: true) { (success, data, _) in

我的错误

  

“由于错误而无法序列化JSON:\ n由于数据格式不正确,因此无法读取。”

最初,我认为这是因为Web服务无法返回正确的JSON,但是如果我从邮递员运行相同的服务,那我就错了,它可以正常工作并且我正在获取JSON格式的数据

我觉得错误是因为传递JSON数据

0 个答案:

没有答案