Extend JSONDecoder to allow for models to be serialized differently based on endpoint

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

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?

Powered by WPeMatico

You may also like...

Comments are closed.