美好的一天我正在努力将数据发布到我的后端我是快速开发的新手请帮助
API希望我发送以下结构:
{
"oid": "string",
"businessKey": "string",
"refNumber": "string",
"name": "string",
"cost": "string",
"clientOid": "string",
"vehicleOid": "string",
"driverOid": "string",
"from": {
"oid": "string",
"businessKey": "string",
"coordinates": [
"string"
],
"address": "string"
},
"to": {
"oid": "string",
"businessKey": "string",
"coordinates": [
"string"
],
"address": "string"
},
"when": "2018-04-09T10:03:01.156Z",
"atp": "2018-04-09T10:03:01.156Z",
"eta": "2018-04-09T10:03:01.156Z",
"ata": "2018-04-09T10:03:01.156Z",
"droplets": [
{
"oid": "string",
"businessKey": "string",
"itemOid": "string",
"description": "string",
"notes": "string"
}
],
"serviceRating": 0,
"notes": "string"
}
这是我的代码:
func createDrop(oid: String, token: String){
let url = getCar.url
let token = "Bearer " + token
var request = URLRequest(url: URL(string: "\(url)drops")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue( token, forHTTPHeaderField: "Authorization")
var parameters: Dictionary<String, Any> = [
"name": "Thami",
"notes": "New",
"cost": "totalPrice",
"clientOid": "clientOi",
"vehicleOid": "vehicleOi",
"driverOid": "driverO",
"when": "dropTime",
"atp": "dropTime",
"eta": "dropTime",
"ata": "dropTime",
"from":[
"coordinates": [
"-26.002483",
"28.099503"
],
"address": "his.distanceInfo.getPickUp()",
],
"to":[
"coordinates": [
"-26.002483",
"28.099503"
],
"address": "this.distanceInfo.getDestination()",
],
"droplets":[
"itemOid": "575ae6bd30bc5d5017477143",
"notes": "new"
]
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
print("serilizing json")
} catch {
print("JSON serialization failed: \(error)")
}
print(parameters)
Alamofire.request(request).responseJSON {(response) in
debugPrint(response)
if response.response?.statusCode == 200 {
print ("pass")
let dropJSON : JSON = JSON(response.result.value!)
print(dropJSON)
}else{
print ("fail gfgdfds")
let dErrorJSON : JSON = JSON(response.result.error!)
print(dErrorJSON)
}
}
}
这是我得到的错误:
[Result]:FAILURE:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain = NSCocoaErrorDomain Code = 3840&#34;字符0周围的值无效。&#34; UserInfo = {NSDebugDescription =字符0周围的值无效) 。}))
如何格式化我的对象以执行此帖子
答案 0 :(得分:1)
尝试对请求中的参数进行编码,例如
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
检查文档以获取更多编码信息 https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#json-encoding