convert an object to json in swift

0

I am currently wanting to convert an object into swift of this class

class UsuarioServer{
var username:String?
var password:String?
var nombreCompleto:String?
var direccion:String?
var edad:String?

init (username: String, password: String, nombreCompleto:String,direccion:String,edad:String) {
    self.username = username;
    self.password = password;
    self.nombreCompleto = nombreCompleto;
    self.direccion = direccion;
    self.edad = edad;
}

init(){}

}

and then I initialize it and set it like this:

       var usuarioServidor:UsuarioServer?
    usuarioServidor?.username = nombreUsuario.text!
    usuarioServidor?.password = password.text!
    usuarioServidor?.direccion = direccion.text!
    usuarioServidor?.nombreCompleto = nombreCompleto.text!

The problem is that I need to send those parameters to an api rest as an NSOBJECT so I thought to serialize it but I do not know how to do it in swift 3 (since I'm new to swift)

some idea of how to transform that object to JSON since I am currently trying to do it this way:

        var usuarioServidor:UsuarioServer?
    usuarioServidor?.username = nombreUsuario.text!
    usuarioServidor?.password = password.text!
    usuarioServidor?.direccion = direccion.text!
    usuarioServidor?.nombreCompleto = nombreCompleto.text!

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: usuarioServidor, options: .prettyPrinted)
        print(jsonData)
    } catch {
        //handle error
        print(error)
    }

but it throws an error (I guess because it's an object)

    
asked by Monster 24.06.2018 в 10:33
source

2 answers

1

What you have to do is put it in a dictionary and then transform it, like a class. You can add a method in the UserServer class that returns that model in dictionary format

func getParams() -> [String: AnyObject] {
    return ["user": self.username as AnyObject,
            "password": self.password as AnyObject,
            "nombre": self.nombreCompleto as AnyObject,
            "direccion": self.direccion as Anyobject,
            "edad": self.edad as Anyobject]
}

If you use Alamofire, with the result of this function, it is responsible for putting it in the JSON format you need. If you want to do it by hand you have to transform it to JSON your

do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data

let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type 'Any', decoded from JSON data

// you can now cast it with the right type        
if let dictFromJSON = decoded as? [String:String] {
    // use dictFromJSON
}
} catch {
  print(error.localizedDescription)
}

This last piece comes from here link

    
answered by 24.06.2018 / 11:54
source
0

You can make use of the JSONEncoder class, which in my opinion is almost magical and elegant.

The first thing you have to do is to adopt the codable type in your class

class UsuarioServer: codable{
  var username:String?
  var password:String?
  var nombreCompleto:String?
  var direccion:String?
  var edad:String?
}

After you have initialized the instance of your object, you can generate the JSON as follows:

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(usuarioServidor)
print(String(data: data, encoding: .utf8)!)
    
answered by 29.06.2018 в 20:18