【发布时间】:2018-02-14 04:14:54
【问题描述】:
我正在尝试将 json 数据发布到预订服务 API。
但是当我点击提交时,我收到 400 错误,导致 “INVALID JSON” 消息。
let urlToRequest = "https://api.bookeo.com/v2/customers?secretKey=" + secretKey + "&apiKey=" + apiKey
func dataRequest() {
let url4 = URL(string: urlToRequest)!
let session4 = URLSession.shared
let request = NSMutableURLRequest(url: url4)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: newParameters)
request.httpBody = dataParameters
//request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("api.bookeo.com", forHTTPHeaderField: "Host")
request.addValue("Keep-Alive", forHTTPHeaderField: "Connection")
request.addValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: [])
print(json as Any)
} //catch {
//print(error)
//}
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("*****This is the data 4: \(String(describing: dataString))") //JSONSerialization
}
task.resume()
}
dataRequest()
我的参数:(“无效的 JSON”)
let parameters: Parameters = [
"eventId": eventId,
"customer": [
"firstName": FirstName.text!,
"lastName": LastName.text!,
"emailAddress": EmailAddress.text!,
"phoneNumbers": [
"number": "123456",
"type": "mobile"
]
],
"participants": [
"numbers": [
"peopleCategoryId": peopleCategoryId,
"number": 1
],
],
"productId": productId,
"initialPayments": [
"reason": "Initial deposit",
"comment": "This is a custom comment",
"amount": [
"amount": "0",
"currency": "USD"
],
"paymentMethod": "creditCard"
]
] as [String : Any]
我的错误回复:
*****This is the data 4: Optional({
"httpStatus": 400,
"message": "Invalid JSON",
"errorId": "1555Q180214041018NWE6T"
})
在使用格式相同的 JSON 之前,我已经使用过这种精确的方法。所以我无法弄清楚为什么这不起作用。
【问题讨论】:
-
您发送的是二进制 plist(带有密钥存档),而不是 JSON。为什么你把
NSJSONSerialization注释掉了?服务器期待请求的形式是什么? -
@Rob 请详细说明。
-
您正在准备使用
NSKeyedArchiver的请求正文。这不会构建 JSON。它正在发回一个响应,说请求的格式不正确。 -
@Rob 好的,我已经切换回来,现在使用
NSJSONSerialization。它仍在返回“无效 JSON”响应。 -
那么很可能是说你发送的 JSON 不包含预期的内容。如果没有更多关于它在 JSON 中的期望的信息,我们无法对此发表评论。
标签: json swift post swifty-json