Created
March 21, 2023 09:21
-
-
Save michaelevensen/c85c44bc179a512e524ddf54933e17c6 to your computer and use it in GitHub Desktop.
Simple custom JSON decoding in Swift for specific keys. Hot tip is to nest the CodingKeys similarly to how the JSON is nested.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Data: Decodable { | |
var age: Int | |
var address: Address | |
struct Address: Decodable { | |
var street: String | |
var city: String | |
} | |
private enum CodingKeys: String, CodingKey { | |
case name, data | |
enum DataKeys: String, CodingKey { | |
case age, address | |
enum AddressKeys: String, CodingKey { | |
case street, city | |
} | |
} | |
} | |
// Implement a custom initializer that takes a Decoder object | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
// Data | |
let dataContainer = try container.nestedContainer(keyedBy: CodingKeys.DataKeys.self, forKey: .data) | |
// Age | |
self.age = try dataContainer.decode(Int.self, forKey: .age) | |
// Address | |
let addressContainer = try dataContainer.nestedContainer(keyedBy: CodingKeys.DataKeys.AddressKeys.self, forKey: .address) | |
let street = try addressContainer.decode(String.self, forKey: .street) | |
let city = try addressContainer.decode(String.self, forKey: .city) | |
self.address = Address(street: street, city: city) | |
} | |
} | |
let json = """ | |
{ | |
"name": "John", | |
"data": { | |
"age": 30, | |
"address": { | |
"street": "123 Main St", | |
"city": "Anytown" | |
} | |
} | |
} | |
""".data(using: .utf8)! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment