Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary to JSON being serialised twice in swift 3

I'm trying to make a post request with the following dictionary which is converted to JSON

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

I am serialising this using the following code and then making a http-POST request using the following options:

        let jsonData = try? JSONSerialization.data(withJSONObject: store)

        var request = URLRequest(url: URL(string: "http://localhost:3000/store")!)
        request.httpMethod = "POST"
        request.httpBody = jsonData

I am also running a json-server https://github.com/typicode/json-server with the following db.json file

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

The problem I am having is that the newly added item in the db looks incorrect with the following format:

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

I am unsure as to why it is serialising the whole dictionary as the key and then an empty string as the value.

Update

Here is the code that posts this to the server:

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

As a side note, I've tried pining this via postman and it all works ok. Attaching a screenshot of it below. enter image description here

Any help will be appreciated, Thanks!

like image 756
Sohil Pandya Avatar asked Jun 05 '17 11:06

Sohil Pandya


1 Answers

When you construct your URLRequest would this line fix it for you?

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

In Postman you are sending it as application/json so I would expect you need to do the same in your swift code.

like image 147
adamfowlerphoto Avatar answered Oct 18 '22 20:10

adamfowlerphoto