2

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?

David
  • 1,648
  • 1
  • 16
  • 31
  • Does this help: https://stackoverflow.com/questions/45598461/swift-4-decodable-with-keys-not-known-until-decoding-time ? – koen Apr 11 '22 at 23:23
  • @koen - Maybe partially, but this is dealing with just a single key being dynamic vs handling fully dynamic structures where all keys and values are dynamic. I am not used to JSON handling being so strongly typed. I may move to a library like SwiftyJSON – David Apr 12 '22 at 00:30
  • The answer is probably to use JSONSerialization – Joakim Danielson Apr 12 '22 at 09:25
  • The more dynamic you make initial parsing, the more you will pay for validating those structures when you are about to use them. A better idea is to have PROPER models (not dictionary), but have those models auto-generated from API. For example Swagger can do it, etc That way on any API change you regenerate the models, and get a compile-time error if any uses of the model are affected. Much better than getting a runtime error, or having to hunt for changed fields in some big dictionary. – timbre timbre Apr 12 '22 at 22:52

1 Answers1

1

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.

Soumya Mahunt
  • 2,148
  • 12
  • 30
  • This is interesting, but I wonder what the speed would be to simply using a library like SwiftyJSON, which is the route I have taken so far. – David Apr 15 '22 at 15:59
  • @David I haven't done any benchmarking comparison with `SwiftyJSON`, but from what I see in its docs the syntax doesn't look good and with `SwiftyJSON` you will have to add your data/type validation compared to what you get with `Codable`. – Soumya Mahunt Apr 15 '22 at 16:20