I\'m looking for a way to automatically serialize and deserialize class instances in Swift. Let\'s assume we have defined the following class …
class Person
Take a look at NSKeyValueCoding.h, specifically setValuesForKeysWithDictionary
. Once you deserialize the json into a NSDictionary
, you can then create and initialize your object with that dictionary instance, no need to manually set values on the object. This will give you an idea of how the deserialization could work with json, but you will soon find out you need more control over deserialization process. This is why I implement a category on NSObject
which allows fully controlled NSObject
initialization with a dictionary during json deserialization, it basically enriches the object even further than setValuesForKeysWithDictionary
can do. I also have a protocol used by the json deserializer, which allows the object being deserialized to control certain aspects, for example, if deserializing an NSArray of objects, it will ask that object what is the type name of the objects stored in the array.