Dynamic API response values for same Codable coding key in Swift

28 Views Asked by At

I'm decoding an API JSON response into a class called Company.

class Company: Codable {
    let id: Int
    let name: String?
    ...
}

One of the elements in the JSON response is called "enabledchat". enabledchat can either carry an INT (i.e. 1) to indicate the company has the chat feature enabled or it can carry a STRING (e.g. "Premium") to indicate that the company would need a "Premium" subscription to use the chat feature.

So Option 1 and 2 below both are legit API responses.

Option 1:

enabledchat: 1

Option 2:

enabledchat: "Premium"

QUESTION:

I would like to achieve 2 things:

  1. Setup Company: Codable in a way that enabledchat can hold both responses of type Int and String (i.e. both Option 1 and 2 above)
  2. Then inject a separate, additional element requiredsubscription into Company during Decode - i.e. ending up with enabledchat: Int and requiredsubscription: String as 2 separate elements / properties in the Company class.

At the end of the decoding process, and instance of Company should look like this in case of Option 1 above:

{
    id: 123
    name: "mycompany"
    enabledchat: 1
    requiredsubscription: "-" 
    ...
}

... and should look like this in case of Option 2 above:

{
    id: 123
    name: "mycompany"
    enabledchat: 0
    requiredsubscription: "Premium" 
    ...
}

I believe the first part can be solved with the answers posted here: How to decode JSON value that can be either string or int

But I'm struggling with the second part - i.e. how to compute the value of element and inject that element into "Company" during the decoding process?

0

There are 0 best solutions below