0

I'm trying to take data return from an API in to an Object. However I am getting errors because the array is complex and not of the same type - it will also differ from the API according to the request made.

let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, Dictionary<String, String>>

The array/data it is being given is as such:

[
   'heartbeatStatus' => 'ok',
    'events' => [
       ['id' => '1', 'name' => 'Event'],
       ['id' => '2', 'name' => 'Event 2'],
    ]         
]

Is there any simple way of doing this? The questions I have seen on SO so far are either for older versions of Swift (this is Swift 5) or aren't are simply different.

The errors I get are like this (different with the various attempts I have made)

Could not cast value of type '__NSSingleObjectArrayI' (0x1ed250b30) to 'NSDictionary' (0x1ed251378). 2020-04-13 18:52:23.173759+0100 removed app id [1209:472869] Could not cast value of type '__NSSingleObjectArrayI' (0x1ed250b30) to 'NSDictionary' (0x1ed251378).

1 Answer 1

1

Try to use Codable. First define a struct to be your model:

struct HeartbeatResponse: Codable { // or whatever

    let heartbeatStatus: String
    let events: [Event]

    struct Event: Codable {

        let id: String
        let name: String

    }

}

Then to decode:

do {
    if let data = data {
        let heartbeat = JSONDecoder().decode(HeartbeatResponse.self, data)
        // do stuff with heartbeat
    }
} catch {
    print(error)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.