I have many models that, depending on the endpoint, or serialized differently. My first attempt had a
init(from decoder: Decoder)
riddled with nested
try catch
blocks. I thought a better solution would be to extend
JSONDecoder
so that when I initialize one, I can specify which endpoint i am pulling from. Then in my models
init(from decoder: Decoder)
I could have a
switch
like
switch
case endpoint1:
x = decoder.decode(Int.self, .x)
case endpoint2:
j = decoder.decode(String.self, .j)
The problem I ran into is that the class you have inside the
init
is a
Decoder
not a
JSONDecoder
. I can't figure out a place that, if I extend
Decoder
and allow myself to specify an endpoint, I could actually specify an endpoint, since
JSONDecoder.decode()
instantiates it's own
Decoder
behind the scenes. Thoughts?
EXAMPLE:
How would you recommend initializing an object from decoder that has say two different variations depending on where you are deserializing it from. For Example
Lets say I get the first book from http://library.com/bookLocations/{id}
And the second book from http://library.com/bookInfo/{id}
Book: {
Author: "James"
Title: "JamesBook"
LibraryId: "387fh384fh3i09"
SectionNumber: "870D"
}
Book: {
Author: "James"
Title: "JamesBook"
Length: "870"
Reviews: "9/10"
}
What is the best way to handle both cases inside
init(from decoder: Decoder)
if I want to use the same model/object for both
struct Book: Codable {
var author: String
var title: String
var libraryId: String?
var sectionNumber: String?
var length: String?
var reviews: String?
}