How to serialize or convert Swift objects to JSON?

后端 未结 9 1754
灰色年华
灰色年华 2020-11-28 03:33

This below class

class User: NSManagedObject {
  @NSManaged var id: Int
  @NSManaged var name: String
}

Needs to be converted to

9条回答
  •  忘掉有多难
    2020-11-28 04:13

    UPDATE: Codable protocol introduced in Swift 4 should be sufficient for most of the JSON parsing cases. Below answer is for people who are stuck in previous versions of Swift and for legacy reasons

    EVReflection :

    • This works of reflection principle. This takes less code and also supports NSDictionary, NSCoding, Printable, Hashable and Equatable

    Example:

        class User: EVObject { # extend EVObject method for the class
           var id: Int = 0
           var name: String = ""
           var friends: [User]? = []
        }
    
        # use like below
        let json:String = "{\"id\": 24, \"name\": \"Bob Jefferson\", \"friends\": [{\"id\": 29, \"name\": \"Jen Jackson\"}]}"
        let user = User(json: json)
    

    ObjectMapper :

    • Another way is by using ObjectMapper. This gives more control but also takes a lot more code.

    Example:

        class User: Mappable { # extend Mappable method for the class
           var id: Int?
           var name: String?
    
           required init?(_ map: Map) {
    
           }
    
           func mapping(map: Map) { # write mapping code
              name    <- map["name"]
              id      <- map["id"]
           }
    
        }
    
        # use like below
        let json:String = "{\"id\": 24, \"name\": \"Bob Jefferson\", \"friends\": [{\"id\": 29, \"name\": \"Jen Jackson\"}]}"
        let user = Mapper().map(json)
    

提交回复
热议问题