0

I would like to represent the following JSON as a struct that conforms to Codable:

{
    "trooper": {"name": "Trooper", "type": "alsatian"},
    "spot": {"name": "Spot", "type": "labrador"},
    "sniffles": {"name": "Sniffles", "type": "poodle"}
}

The list is not exhaustive i.e. there can be any number of dogs in the list.

The {"name": "Sniffles", "type": "poodle"} part is easy, and can be done like this:

struct Dog: Codable {
    var name: String
    var type: String
}

But what about the root level?

naudecruywagen
  • 378
  • 3
  • 8

1 Answers1

1

This is what I was looking for:

let str = """
{
    "trooper": {"name": "Trooper", "type": "alsatian"},
    "spot": {"name": "Spot", "type": "labrador"},
    "sniffles": {"name": "Sniffles", "type": "poodle"}
}
"""

struct Dog: Codable {
    var name: String
    var type: String
}

if let data = str.data(using: .utf8) {

    do {
        let decoder = JSONDecoder()
        let dogs = try decoder.decode([String: Dog].self, from: data)
        print(dogs)
    } catch {
        print(error)
    }

}
naudecruywagen
  • 378
  • 3
  • 8