Search code examples
swiftobjectmapper

ObjectMapper and arrays with unique keys


Im running into an issue with ObjectMapper and the way a json response is coming back from a server. Is there a way to have ObjectMapper parse this response and create an array of rooms?

Currently I cannot straight map the json as the keys are unique, and will change every request, as well I cannot use the ObjectMapper way of accessing nested objects with dot notation, rooms.0.key as I am unsure how many objects there are, as well as the key that will show up.

Is there a simple way of parsing this reponse.

enter image description here

"rooms": {
        "165476": {
            "id": "165476",
            "area": {
                "square_feet": 334,
                "square_meters": 31
            },
        "165477": {
            "id": "165477",
            "area": {
                "square_feet": 334,
                "square_meters": 31
            },

Solution

  • Use Codable to parse the above JSON response.

    Models:

    struct Rooms: Codable {
        let rooms: [String:Room]
    }
     
    struct Room: Codable {
        let id: String
        let area: Area
    }
    
    struct Area: Codable {
        let squareFeet: Int
        let squareMeters: Int
    }
    

    Parse the JSON data like so,

    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let response = try decoder.decode(Rooms.self, from: data)
        print(response.rooms.first?.key) //for the above json it will print "165476"
    } catch {
        print(error)
    }