Automatic JSON serialization and deserialization of objects in Swift

前端 未结 7 2020
走了就别回头了
走了就别回头了 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条回答
  •  -上瘾入骨i
    2020-12-13 00:50

    You can achieve this by using ObjectMapper library. It'll give you more control on variable names and the values and the prepared JSON. After adding this library extend the Mappable class and define mapping(map: Map) function.

    For example

       class User: Mappable {
           var id: Int?
           var name: String?
    
           required init?(_ map: Map) {
    
           }
    
           // Mapping code
           func mapping(map: Map) {
              name    <- map["name"]
              id      <- map["id"]
           }
    
        }
    

    Use it like below

       let user = Mapper().map(JSONString)
    

提交回复
热议问题