API 在 Postman 中工作但在代码中给出错误

API working in Postman but giving error in Code

我试图在邮递员中调用 API 并且它工作正常,但是如果我试图在 swift Alamofire 中调用 API,它给我错误-

我的代码是-

func sendToServer(){
        let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
        
        let data:  Parameters = ["SerialNo": "T8180399","Status":101]
        

        Alamofire.request(urlString, method: .post, parameters: data,encoding: JSONEncoding.default, headers: nil).responseJSON {
        response in
          switch response.result {
                        case .success:
                            print(response)

                            break
                        case .failure(let error):

                            print(error)
                        }
        }
    }

错误是-

The JSON value could not be converted to System.Collections.Generic.List`1[BreakBulkModels.Model.WebapiModels.DtoInventoryApi]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

您的 API 接受一个 JSON 对象数组作为参数,但您当前正在发送一个 JSON 对象:

{
    "SerialNo": "T8180399",
    "Status": 101
}

因为ParametersDictionary<String, Any>的类型别名(你需要的是Array<Dictionary<String, Any>>)你必须自己做你的参数编码然后调用Alamofire的request(_:)函数通过你的 URLRequest:

do {
    let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
    let url = try urlString.asURL()
    var request = URLRequest(url: url)
    let data = [["SerialNo": "T8180399", "Status": 101]]
    request = try JSONEncoding.default.encode(request, withJSONObject: data)
    Alamofire.request(request).responseJSON { response in
        switch response.result {
        case .success:
            print(response)
            break
        case .failure(let error):
            print(error)
        }
    }
} catch {
    print(error)
}

编辑:对于 Alamofire v5,使用 Encodable 协议有一种更优雅的方式:

struct BarCode: Encodable {
    var SerialNo: String
    var Status: Int
}

func sendToServer(){
    let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
    let data = [BarCode(SerialNo: "T8180399", Status: 101)]
    AF.request(
        urlString,
        method: .post,
        parameters: data,
        encoder: JSONParameterEncoder.default
    ).responseJSON { response in
        switch response.result {
        case .success:
            print(response)
            break
        case .failure(let error):
            print(error)
        }
    }
}