Maurizio Terreni Maurizio Terreni - 26 days ago 12
iOS Question

serialization and de-serialization of an object in Swift3

I want to know if there is a possibility of make a serialization and de-serialization of an object in swift 3.

I have an object like this:

class Credentials{
var username:String;
var password:String;
init(){
username = "";
password = "";
}
}


I want to transform this class into a json (and vice versa ) to send it through HTTP post.

I don't want to use Third party libraries.

Thanks for the answer.

Answer

First of all it's not necessary to use a class, a struct is sufficient.

Simple solution with an failable initializer expecting a JSON string and a variable jsonRepresentation

struct Credentials {
   var username = ""
   var password = ""

   init(username: String, password:String) {
      self.username = username
      self.password = password
   }

   init?(json : String) {
      guard let data = json.data(using: .utf8),
         let jsonDict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:String],
         let username = jsonDict?["username"],
         let password = jsonDict?["password"] else { return nil }
      self.username = username
      self.password = password
   }

  var jsonRepresentation : String {
     let jsonDict = ["username" : username, "password" : password]
     if let data = try? JSONSerialization.data(withJSONObject: jsonDict, options: []),
        let jsonString = String(data:data, encoding:.utf8) {
        return jsonString
     } else { return "" }
  }
}
Comments