Created
September 18, 2021 21:44
-
-
Save IanKeen/c301960834d5500be4512da13e12c6eb to your computer and use it in GitHub Desktop.
Decode an object nested under a key
This file contains 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
let json = """ | |
{ | |
"results": [ | |
{"value": "foo"}, | |
{"value": "bar"}, | |
{"value": "baz"} | |
] | |
} | |
""" | |
struct Item: Decodable { | |
let value: String | |
} | |
let items = try JSONDecoder().decode([Item].self, from: Data(json.utf8), under: "results") | |
print(items) // [Item(value: "foo"), Item(value: "bar"), Item(value: "baz")] |
This file contains 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
extension TopLevelDecoder { | |
func decode<T: Decodable>(_ type: T.Type, from input: Input, under: String) throws -> T { | |
let decoder = try decode(_Decoder.self, from: input).decoder | |
let container = try decoder.container(keyedBy: AnyCodingKey.self) | |
return try container.decode(T.self, forKey: .init(under)) | |
} | |
} | |
private struct _Decoder: Decodable { | |
var decoder: Decoder | |
init(from decoder: Decoder) throws { | |
self.decoder = decoder | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AnyCodingKey: https://gist.github.com/IanKeen/3d226854c8c59a17e151a0022b71f6bb