Soh*_*dya 11 json nsdictionary nsjsonserialization swift
我正在尝试使用以下字典进行发布请求,该字典转换为JSON
let store = [
"newTask" : [
"project_name": "iOS",
"total_time":0,
"color":"blue"
]
]
Run Code Online (Sandbox Code Playgroud)
我使用以下代码将其序列化,然后使用以下选项发出http-POST请求:
let jsonData = try? JSONSerialization.data(withJSONObject: store)
var request = URLRequest(url: URL(string: "http://localhost:3000/store")!)
request.httpMethod = "POST"
request.httpBody = jsonData
Run Code Online (Sandbox Code Playgroud)
我还使用以下db.json文件运行json-server https://github.com/typicode/json-server
{
"store": [
{
"id": 0,
"ios": {
"project_name": "iOS",
"total_time": 0,
"color": "blue"
}
},
{
"id": 1,
"elm": {
"project_name": "elm",
"total_time": 0,
"color": "blue"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是db中新添加的项看起来不正确,格式如下:
{
"{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "",
"id": 10
},
Run Code Online (Sandbox Code Playgroud)
我不确定为什么它将整个字典序列化为键,然后将空字符串作为值.
更新
以下是将此发布到服务器的代码:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
}
} catch let error {
print(error.localizedDescription)
}
}
task.resume()
Run Code Online (Sandbox Code Playgroud)
作为旁注,我试过通过邮递员来解决这个问题,一切正常.在下面附上它的截图.

任何帮助将不胜感激,谢谢!
当您构建 URLRequest 时,这一行会为您修复它吗?
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Run Code Online (Sandbox Code Playgroud)
在 Postman 中,您将其作为 application/json 发送,因此我希望您需要在 swift 代码中执行相同的操作。
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |