无法在Swift 4.0中将对象数组发布到Web API

时间:2019-12-31 06:31:58

标签: json swift post webapi

快捷代码:

func set(data:[AirFreightModel],userid:String,username:String,completion:@escaping(Result<String,CustomError>)->Void)
{
    let url = URL(string: "\(CS.ServerName)/AirFreight/SetAirFreightApproval?UserID=\(userid)&UserName=\(username)")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    //request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    do{
        let jsonData = try! JSONEncoder().encode(data)
        let jsonString = String(data: jsonData, encoding: .utf8)!
        print(jsonString)

        let parameters: [String: String] = [
            "AirFreight": jsonString
        ]
        //request.httpBody = parameters.percentEncoded()
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions())
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data,
                let response = response as? HTTPURLResponse,
                error == nil else {                                              // check for fundamental networking error
                    print("error", error ?? "Unknown error")
                    return
            }

            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }

            do{
                let decoder=JSONDecoder()
                let userResponse=try decoder.decode(String.self, from: data)
                completion(.success(userResponse))
            }catch
            {
                print("Unexpected  error: \(error)")
                completion(.failure(.canNotProcessData))
            }
        }
        task.resume()
    }
    catch
    {

    }

}

Web API代码:

public string SetAirFreightApproval(List<AirFreightModel> AirFreight,string UserID,String UserName)
{
return "1";
}

对Web api的请求非常完美,因此QueryString变量数据可以正常工作,但是无法传递对象数据数组。我是Swift的新手,所以不知道我在搞什么。我正在使用Swift 4.2。和xcode 10。 样本JSON字符串:

[
  {
    "CauseID": " Matha Nosto Man",
    "CompanyName": "",
    "RaciActionList": [

    ],
    "PoType": "",
    "CauseDescription": "",
    "FBID": "Test",
    "ResponseResult": "",
    "RACI": "",
    "Destination": "",
    "Remarks": "",
    "Sequence": "",
    "Type": "",
    "BillDate": "",
    "FreightType": "",
    "BillAmount": "",
    "BillRef": "",
    "CommandName": "",
    "IsChecked": false,
    "EmployeeCode": "",
    "BuyerORExporter": "",
    "Mode": "",
    "Forwarder": "",
    "RunningFor": ""
  }
]

TIA

1 个答案:

答案 0 :(得分:0)

如果Web API期望主体中包含JSON(如我所期望的那样),则准备请求应如下所示(直接在此处键入,因此可能是错别字)

let parameters = [
    "AirFreight": data
]
// options by default [], so can be dropped
request.httpBody = try JSONSerialization.data(withJSONObject: parameters) 
// your can print debug of request.httpBody after serialisation to check

这将发送完整的JSON对象

{
   "AirFreight": [
     {
       "CauseID": " Matha Nosto Man",
       "CompanyName": "",
       "RaciActionList": [

        ],
        "PoType": "",
        ...
   ]
}

提供您的代码快照相反,该代码快照生成一个项目JSON,例如(临时)

{
   "AirFreight": "Very long flat string containing all objects properties"
}