I don’t know anything about Evreflection, but I can help you serialize your json using Swift Jsonserialization native API to convert json data:
First Voce should get used to always using structs instead of classes if it is not subclassing Nsobject or another class.
Do not use IUO (implicitly unwrapped optional) if it is not necessary and do not add the name of your class or structure to the name of its properties. Always start with Let when declaring your properties. In short, create a structure with a fallible initializer as follows:
struct Ingredient {
let id: Int
let nome: String
let adicional: Bool
let valorAdicional: Double
let empresa: Int
init?(json: Data) {
guard let json = (try? JSONSerialization.jsonObject(with: json, options: [])) as? [String: Any] else { return nil }
self.id = json["idIngrediente"] as? Int ?? 0
self.nome = json["nomeIngrediente"] as? String ?? ""
self.adicional = json["adicional"] as? Bool ?? false
self.valorAdicional = json["valorAdicional"] as? Double ?? 0
self.empresa = json["empresa"] as? Int ?? 0
}
}
Testing
let json = "{\"adicional\":false,\"empresa\":500,\"idIngrediente\":508,\"valorAdicional\":1.99,\"nomeIngrediente\":\"Ketchup\"}"
let data = Data(json.utf8)
if let ingredient = Ingredient(json: data) {
print(ingredient.id) // "508\n"
print(ingredient.nome) // "Ketchup\n"
print(ingredient.adicional) // "false\n"
print(ingredient.valorAdicional) // "1.99\n"
print(ingredient.empresa) // "500\n"
}
Opa Leo, thanks for the answer, I had asked a question also in evreflection’s git and it’s pretty simple to implement all this again. But in case you need I already have your example. Thank you very much!!
– Bruno Nicoletti