字典到JSON在swift 3

时间:2017-06-05 11:35:15

标签: json swift nsdictionary nsjsonserialization

我正在尝试使用以下字典进行发布请求,该字典转换为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

我还在运行带有以下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"
    }
  }
]
}

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

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

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

更新

以下是将此帖子发布到服务器的代码:

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

作为旁注,我试过通过邮递员来解决这个问题,这一切都很有效确定。在下面附上它的截图。 enter image description here

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

1 个答案:

答案 0 :(得分:2)

当你构建你的URLRequest时,这行会为你解决吗?

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

在Postman中你将它作为application / json发送,所以我希望你需要在你的swift代码中做同样的事情。