使用 Alamofire 在 Swift 中发布嵌套 JSON
Posted
技术标签:
【中文标题】使用 Alamofire 在 Swift 中发布嵌套 JSON【英文标题】:posting nested JSON in Swift with Alamofire 【发布时间】:2018-04-10 12:43:59 【问题描述】:美好的一天,我目前正在努力将数据发布到我的后端我是快速开发的新手,请帮助
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)
这是我得到的错误:
[结果]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "字符 0 附近的值无效。" UserInfo=NSDebugDescription=字符 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
【讨论】:
以上是关于使用 Alamofire 在 Swift 中发布嵌套 JSON的主要内容,如果未能解决你的问题,请参考以下文章
使用 Alamofire 在 Swift 中发布嵌套 JSON
Alamofire 在 Swift 3、Xcode 8 中出现错误
使用 swift 在 Alamofire 中使用 CURL 命令