I'm receiving the same json structure from two endpoints, the only thing different are the keys in the json. On response #1 I get
[
{
"id": 45,
"chapter__book__name": "Alonso",
"chapter__book__id": 70,
"chapter__chapter": 2,
"verse": "",
"verse_number": 5,
"chapter": 97
},
]
And on response #2 I get:
[
{
"id": 962,
"book_name": "Title here",
"book_id": 70,
"chapter_number": 32,
"verse": "xxx",
"verse_number": 24,
"chapter": 127
},
]
Can one struct decode both of these? Currently my struct looks like this:
struct Verse: Decodable, Identifiable {
let id: Int
let book_name: String
let book_id: Int
let verse: String
let verse_number: Int
let chapter: Int // chapter Id in database
let chapter_number: Int
}
Which matches response #2, but not response #1.
@lorem ipsum's method should work I didn't try it myself with swiftUI, however it feels a bit convoluted to deal with 2 different types of object. Eventhough they share a common protocol, since it's the same object that will be decoded, it seems natural to keep track of one single type.
As stated by @Larme it can be done with a custom
init(from decoder: Decoder)method.This code works on playground
SideNotes:
The whole point is to juggle with two different
CodingKeys.since this evolution it is now feasible to make an enum conform to protocols, which I didn't now of before diving into your issue. This makes the code more straightforward and reusable.
There may be a better way to handle the
do catchmechanism but it's acceptable at this point. as stated by @Cristik in comment, you should enhance the error handling mechanism because you don't want to let all the error going through. see his comment belowThis is how far I could get with this little experiment, I reckon someone will be able to do better. It still seem more reliable to use a single concrete class instead of two plus a protocol, but again, I'm not pretending to be an expert.