Automatic JSON serialization and deserialization of objects in Swift

前端 未结 7 2059
走了就别回头了
走了就别回头了 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:34

    You could use EVReflection for that. You can use code like:

    var person:Person = Person(json:jsonString)
    

    or

    var jsonString:String = person.toJsonString()
    

    See the GitHub page for more detailed sample code. You only have to make EVObject the base class of your data objects. No mapping is needed (as long as the json keys are the same as the property names)

    Update: Swift 4 has support for Codable which makes it almost as easy as EVReflection but with better performance. If you do want to use an easy contractor like above, then you could use this extension: Stuff/Codable

提交回复
热议问题