My data looks like this:
"places": [
{
"id": 15,
"name": "København",
"typeId": 6,
"coordinates": {
"lat": "55.6760968",
"lng": "12.5683372"
},
"count": 2779
},
{
"id": 19,
"name": "København S",
"typeId": 3,
"coordinates": {
"lat": "55.6508754",
"lng": "12.5991891"
},
"count": 1168
}
]
I wish to avoid this:
struct Places: Decodable {
let places: [Place]
}
Which is suggested by QuickType.io: https://app.quicktype.io?share=j22hopuBnkuHZziOSvxG And instead just decode within "places" list. Such that this would work:
let places = try JSONDecoder().decode([Place].self, from: data)
Possible solutions that I've found so far:
The 'Scuffed' solution: https://stackoverflow.com/a/62403633/13481876
Create generic decodable array struct: https://swiftsenpai.com/swift/decode-dynamic-keys-json/
If you find yourself needing this multiple times, then you can build your own generic struct that decodes over whichever key it finds:
And with this in hand, you can extend
JSONDecoder
in order to get a nicer call site:Then it's just a matter of calling the new overload:
P.S. if you want, you can hide the complex struct within the extension, resulting in something like this:
The downside is that you'll not be able to reuse the struct if you want to extend other decoders besides the JSON one.