Skip to content

Instantly share code, notes, and snippets.

@daneden
Created July 24, 2021 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daneden/2e37ff3dc96efc9e53746d757ba0d2be to your computer and use it in GitHub Desktop.
Save daneden/2e37ff3dc96efc9e53746d757ba0d2be to your computer and use it in GitHub Desktop.

I’m trying to decode two slightly different JSON API responses to the same Codable type, Account. Mapping userResponse.json’s uid to id is trivial, but extracting the nested user is stumping me.

Any suggestions would be greatly appreciated!

struct Account: Codable {
typealias ID = String
var id: ID
var uid: String?
var avatar: String?
var name: String
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let id = try values.decodeIfPresent(String.self, forKey: .uid) {
self.id = id
} else {
self.id = try values.decode(String.self, forKey: .id)
}
self.avatar = try values.decode(String.self, forKey: .avatar)
self.name = try values.decode(String.self, forKey: .name)
}
}
{
"id": "team_ba3d8621-3c66-421a-8c46-f1ea6dfa27a1",
"name": "Acme, Inc.",
"avatar": "02d2608a-7526-4821-ad27-3d329b674dc8",
}
{
"user": {
"uid": "f5f5e86e-b75e-4cc7-a3be-ddeecbd9c7a6",
"name": "John Appleseed",
"avatar": "9283df3f-54d3-4329-8d6b-dbc90f8a9a38"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment