Ios – Turn swift object into a JSON string

iosjsonswiftswift3

I have classes like these:

class MyDate
  {
    var year : String = ""
    var month : String = ""
    var day : String = ""

    init(year : String , month : String , day : String) {
        self.year = year
        self.month = month
        self.day = day
    }

}

class Lad
{
    var firstName : String = ""
    var lastName : String = ""
    var dateOfBirth : MyDate?

    init(firstname : String , lastname : String , dateofbirth : MyDate) {
        self.firstName = firstname
        self.lastName = lastname
        self.dateOfBirth = dateofbirth
    }
}

class MainCon {

    func sendData()  {


        let myDate = MyDate(year: "1901", month: "4", day: "30")
        let obj = Lad(firstname: "Markoff", lastname: "Chaney", dateofbirth: myDate)

        let api = ApiService()
        api.postDataToTheServer(led: obj)

    }

}

class ApiService {

    func postDataToTheServer(led : Lad)  {
        // here i need to json
    }
}

And I would like to turn a Lad object into a JSON string like this:

{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}

Best Answer

EDIT - 10/31/2017: This answer mostly applies to Swift 3 and possibly earlier versions. As of late 2017, we now have Swift 4 and you should be using the Encodable and Decodable protocols to convert data between representations including JSON and file encodings. (You can add the Codable protocol to use both encoding and decoding)

The usual solution for working with JSON in Swift is to use dictionaries. So you could do:

extension Date {
  var dataDictionary {
    return [
      "year": self.year,
      "month": self.month,
      "day": self.day
    ];
  }
}

extension Lad {
  var dataDictionary {
    return [
      "firstName": self.firstName,
      "lastName": self.lastName,
      "dateOfBirth": self.dateOfBirth.dataDictionary
    ];  
  } 
}

and then serialize the dictionary-formatted data using JSONSerialization.

//someLad is a Lad object

do {
  // encoding dictionary data to JSON
  let jsonData = try JSONSerialization.data(withJSONObject: someLad.dataDictionary, 
                                                   options: .prettyPrinted)

  // decoding JSON to Swift object
  let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
  // after decoding, "decoded" is of type `Any?`, so it can't be used
  // we must check for nil and cast it to the right type        
  if let dataFromJSON = decoded as? [String: Any] {
      // use dataFromJSON
  }
} catch {
    // handle conversion errors
}

If you just need to do this for few classes, providing methods to turn them into dictionaries is the most readable option and won't make your app noticeably larger.

However, if you need to turn a lot of different classes into JSON it would be tedious to write out how to turn each class into a dictionary. So it would be useful to use some sort of reflection API in order to be able to list out the properties of an object. The most stable option seems to be EVReflection. Using EVReflection, for each class we want to turn into json we can do:

extension SomeClass: EVReflectable { }

let someObject: SomeClass = SomeClass();
let someObjectDictionary = someObject.toDictionary();

and then, just like before, we can serialize the dictionary we just obtained to JSON using JSONSerialization. We'll just need to use object.toDictionary() instead of object.dataDictionary.

If you don't want to use EVReflection, you can implement reflection (the ability to see which fields an object has and iterate over them) yourself by using the Mirror class. There's an explanation of how to use Mirror for this purpose here.

So, having defined either a .dataDictionary computed variable or using EVReflection's .toDictionary() method, we can do

class ApiService {

  func postDataToTheServer(lad: Lad)  {
    //if using a custom method
    let dict = lad.dataDictionary

    //if using EVReflection
    let dict = lad.toDictionary()

    //now, we turn it into JSON
    do {
      let jsonData = try JSONSerialization.data(withJSONObject: dict, 
                                                       options: .prettyPrinted)
      // send jsonData to server
    } catch {
      // handle errors
    }
  }
}