Automatic JSON serialization and deserialization of objects in Swift

前端 未结 7 2018
走了就别回头了
走了就别回头了 2020-12-13 00:21

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          


        
相关标签:
7条回答
  • 2020-12-13 00:54

    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.

    0 讨论(0)
提交回复
热议问题