Maurizio Terreni Maurizio Terreni -4 years ago 154
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;
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 Source

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 = .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? jsonDict, options: []),
        let jsonString = String(data:data, encoding:.utf8) {
        return jsonString
     } else { return "" }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download