Search code examples
jsonswiftnsjsonserialization

Cannot convert Data to NSDictionary


I'm trying to convert data from URLSession to a NSDictionary but it fails when converting the data to dictionary.

Following:

let json = try? JSONSerialization.jsonObject(with: data!, options: [])
print(json ?? "NotWorking")

outputs

(
  {
    babyId = 1;
    id = 17;
    timestamp = "2018-06-30 09:23:27";
  }
)

But when I try to convert it into a Dictionary with following it outputs nil.

let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

The webpage outputs

[{"id":"17","babyId":"1","timestamp":"2018-06-30 09:23:27"}]

Where does the error occurs?


Solution

  • [ ] means array in JSON. { } means dictionary. You have an array of dictionary. Note that when you print an array in Swift, you will see ( ).

    Don't use NSArray or NSDictionary in Swift without a very clearly understood and specific reason. Use a Swift array and dictionary of the proper types.

    Your code should be:

    do {
        if let results = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
            // results is now an array of dictionary, access what you need
        } else {
            print("JSON was not the expected array of dictonary")
        }
    } catch {
        print("Can't process JSON: \(error)")
    }
    

    And really you shouldn't be using data! either. Somewhere above this you should have a if let data = data {