Penkey Suresh Penkey Suresh - 1 year ago 98
iOS Question

How to convert or parse swift objects to JSON?

Is there a library or method which can help me to convert Swift objects to JSON (like gson for Java)?

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

Needs to be converted to

"id" : 98,
"name" : "Jon Doe"

I tried manually setting the variable into a dictionary through a function. But given the object is very big compiling is taking forever

The function I tried to use to accomplish this task.

class func getJson(data : User) -> NSDictionary {
let json : [String: Any?] = ["id":, "name":, ... 21... values ]

Answer Source

Finally I solved this issue by using ObjectMapper library

Pasting conversion code here for ease of reference.

  • Add the library to your project
  • Extend Mappable class for objects you want mapping for
  • Implement mapping(map: Map) class with desired mapping.

    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<User>().map(JSONString)