Dictionary to JSON being serialised twice in swift 3
Asked Answered
O

1

11

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!

Oxidase answered 5/6, 2017 at 11:35 Comment(2)
@EricAya Thanks for getting in touch so quickly! I've updated the above post with an update posting the http request as well as explaining that the same request on postman works ok.Oxidase
@EricAya I've changed it so that the key name is exactly the same. It seems to work fine on postman. Issues are most likely related to the HTTP request or the serialization that is happening.Oxidase
A
2

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.

Advocaat answered 5/6, 2017 at 14:24 Comment(1)
Perfect! was not aware of that. I kept on looking at the response and the response type was set to application/json so thought that the post request was of the same type. This solves it for me! :tada: Thansk!Oxidase

© 2022 - 2024 — McMap. All rights reserved.