Using Codable with object under single root key

      No Comments on Using Codable with object under single root key

While using codable we come across situations when our object keys are not at the root level

//Final code

/*
JSON data
{
  "dog": {
    "id": 1,
    "task": "bow wow"
  }
}*/

struct Dog: Codable {
  let id: Int
  let task: String
}

let decoder = JSONDecoder()
let userDictionary = try decoder.decode([String: Dog].self, from: jsonData)
let dogObj = userDictionary["dog"]

 

Now that we have our concerned properties “id” and “task” under “dog” key we can make our dog struct like

struct Dog: Codable {
  let id: Int
  let task: String
}

and a wrapper struct to take care  of outer “dog” key like

struct DogWrapper: Codable {
  let dog: Dog
}

this can be directly decoded from json like

let decoder = JSONDecoder()
let userDictionary = try decoder.decode(DogWrapper.self, from: jsonData)

this will give as a dogwrapper object with the dog as its property.

Now we can get dog object without wrapper struct by getting a dictionary of dog object for dog key. Because the JSON is theoretically “dog” object under “dog” key.So we can get it without DogWrapper as shown below

let decoder = JSONDecoder()
let userDictionary = try decoder.decode([String: Dog].self, from: jsonData)

Now the outer key “dog” has our Dog object as its value

A pat on the back !!