Search Your Question

What is Object mapping that helping Jon parsing?

Ans. : Object mapping is convert to JSON to SomeOtherObject, BussinessModel to PersistenceModel, etc or map fields of JSON to SomeOtherObject fields.

There are many third party library available for same purpose.

1. We use mapping using init method without third party library :

struct User {
  let id: Int
  let name: String
  
  init?(dictionary: [String: Any]) {
    guard let id = dictionary["id"] as? Int else { return nil }
    guard let name = dictionary["user_name"] as? String else { return nil }
    
    self.id = id
    self.name = name
  }
}

do {
  if let userDictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
    let user = User(dictionary: userDictionary)
    //Do something with user
  }
} catch {
  print(error)

}

3. Using codable protocol  (Without third party)
4. SwiftyJson 

In today's world mostly people using 3rd option for  object mapping.

No comments:

Post a Comment

Thanks