【问题标题】:Can not Post Array of object to web api in swift 4.0无法在 swift 4.0 中将对象数组发布到 web api
【发布时间】:2019-12-31 06:31:58
【问题描述】:

Swift 代码:

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
    {

    }

}

网页 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

在哪里显示了对 web api 的请求已被完全发出,因为其余参数获取的所有值都接受列表之一。

【问题讨论】:

  • 我不明白。什么是“示例 JSON 字符串:”?想要的输出?您当前在 Swift 中的输出?你是从哪里打印出来的?您的代码中有错误代码,而且您是说参数是 url 编码的,但是发送 JSON?
  • 不,这是我尝试发送到 Web Api 的内容。如果你查看我的代码,你会看到有一个打印语句,我从那里得到这个 JSON 字符串。我尝试将其发送到 Web Api Server。我的代码中可能有任何错误代码,因为我告诉我我是 swift 新手,所以我的大部分代码都来自互联网,你能指出哪一个不合适吗?

标签: json swift post webapi


【解决方案1】:

如果 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 的代码快照相反,例如 (scratchy)

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

【讨论】:

  • 我认为 let parameters: [String: String] = [ "AirFreight": jsonString ] 和 let parameters= [ "AirFreight": jsonString ] 两者是相同的语句,一个是明确定义数据类型,另一个是隐含的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 2015-01-15
  • 2018-01-25
  • 2019-06-26
  • 1970-01-01
相关资源
最近更新 更多