How do you efficiently handle highly dynamic JSON structures in Swift?

Viewed 55

I am writing a Swift program to interact with our backend Database. These database tables can change format, and each row is from DynamoDB and is represented by a JSON object. Within the program, it will grab the cache from the server which contains the Database structures and then the current contents of the database. I don't want to hardcode the database structures into the app as that would obviously make this too very hard to maintain. What is the best way to read in these rows into a generic dictionary object with dynamic names that can hold any of the JSON types?

1 Answers

One way you can handle parsing dynamic JSON is to have a key or a set of keys that gives information about which type of model to decode. For example, you can have a key type in your JSON objects:

{
...
  "type": "some type"
...
}

and an intermediate model:

struct IntermediateModel: Codable {
  let type: String // or enum
}

you first decode all your JSON objects to the intermediate model and then decode them to the actual model type based on the value of type.

I have written some helper protocols that make this easier here.

Related