JSON 的字典在 swift 中被序列化两次 3

Dictionary to JSON being serialised twice in swift 3

我正在尝试使用以下字典发出 post 请求,该字典已转换为 JSON

    let store = [
        "newTask" : [
            "project_name": "iOS",
            "total_time":0,
            "color":"blue"
        ]
    ]

我正在使用以下代码对此进行序列化,然后使用以下选项发出 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

我也是运行一个json服务器https://github.com/typicode/json-server,有以下db.json文件

{
 "store": [
  {
    "id": 0,
    "ios": {
      "project_name": "iOS",
      "total_time": 0,
      "color": "blue"
    }
  },
  {
    "id": 1,
    "elm": {
      "project_name": "elm",
      "total_time": 0,
      "color": "blue"
    }
  }
]
}

我遇到的问题是数据库中新添加的项目看起来不正确,格式如下:

{
  "{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "",
  "id": 10
},

我不确定为什么将整个字典序列化为键,然后将一个空字符串序列化为值。

更新

这是 post 发送到服务器的代码:

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()

附带说明一下,我已经尝试通过 postman 固定它并且一切正常 ok。下面附上它的截图。

任何帮助将不胜感激,谢谢!

当您构造 URLRequest 时,这行代码会为您修复它吗?

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

在 Postman 中,您将其作为 application/json 发送,因此我希望您需要在 swift 代码中执行相同的操作。