我使用的是随Swift4提供的JSONEncoder。 我有一个名为Customer的类,它使用Codable协议。客户内部有四个字符串。
class Customer: Codable {
var title: String
var firstName: String
var lastName: String
var email: String
}
使用GET请求读取JSON工作正常。
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
let customer = try JSONDecoder().decode(Customer.self, from: data)
DispatchQueue.main.async {
print("\(customer.title)")
print("\(customer.firstName)")
print("\(customer.lastName)")
print("\(customer.email)")
}
} catch let jsonError {
print(jsonError)
}
}.resume()
然而,当我开始做POST请求时,我迷路了:
首先设置请求对象:
let urlString = "http://localhost:8000/customer"
guard let url = URL(string: urlString) else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
let customer = Customer()
customer.title = "Mr"
customer.firstName = "Chuck"
customer.lastName = "Norris"
customer.email = "chuck.norris@awsome.com"
let encodedData = try? JSONEncoder().encode(customer)
print(String(data: encodedData!, encoding: .utf8)!) //<- Looks as intended
// Output is {"firstName":"Chuck","lastName":"Norris","title":"MR","email":"chuck.norris@awesome.com "}
现在发送出去
request.httpBody = encodedData //
URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.data(withJSONObject: data, options: [])
print(json)
}catch {
print(error)
}
}
})
作为回报,我收到消息“给定数据无效JSON。”
所以,我的假设是我不能只将编码的JSON数据放入我的请求的http主体中。
浏览一些关于URLSession和JSON的文章我发现我似乎需要序列化我编码的JSON:
var json: Any?
if let data = encodedData {
json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
}
现在,我不知道如何继续。首先,我不明白为什么我应该将我的JSON序列化为不能简单地放入httpBody的东西。 因为JSONSerialization.jsonObject产生Any?而不是数据。
更新 现在,我能够成功将数据发送到我的服务器。我仍然试图理解错误的原因 - 因为我没有改变任何东西(除了在完成处理程序中删除JSONSerialization调用。我将进一步调查... ......而且.resume已经失踪了。 : - )