Sublass in JSON

Hey all,


I'm working on a project which includes a large collection of objects to be displayed to the user in a table view. I decided to store data on my objects in a JSON file, but am struggling when it comes to various subclassed objects.


For example, all objects are sublclassed from Car, and can be any number of different models (each with different properties). Is it reasonable to think that trying to decode one large JSON file with many Car subclasses in it is even worth the struggle of setting up a proper decoder?


To those curious, here's a simplified structure of my JSON file, where "allModels" is an array containing objects with unique types (the name property correlates to the subclass name in my code), and an array of objects which are all the type declared in their respective objects. I essentially have a heterogeneous array of homogeneous objects.


{
    "name": "All Cars",
    "allModels": [
        {
            "name": "Chevy",
            "IndividualCars": [
                {
                    "color": "blue",
                    "wheels": 4
                }, {
                    "color": "red",
                    "wheels": 4
                }
            ]
        }, {
            "name": "Honda",
            "IndividualCars": [
                {
                    "color": "blue",
                    "wheels": 4,
                    "hasHondaThing": true
                }, {
                    "color": "red",
                    "wheels": 4,
                    "hasHondaThing": false
                }
            ]
        }
    ]
}


Any insight would be much appreciated!

-Reece

Replies

If I understand what you do…


I would decode all properties for all objects.

If missing, then I get a njil and handle appropriately.


To illustrate:

even for "Chevy", I would try to decode

"hasHondaThing"

which of course would yield nil.


That is what you do in a plist: come items have a property, others don't.

That's the nice thing with a dictionary !

Generally, Swift Codable is based on static type system and does not fit for subclassing.

You could write a huge lines of code to implement `Decodable` manually.

And of course you might need to update the code at each time you add a new subclass.


---

One option, just define a single struct `Car`, in which you can define optional properties.

struct Car: Codable {
    var color: String
    var wheels: Int
    
    var hasHondaThing: Bool?
    //...
}


Or there may be better options, to find which would be your best, please show more info.