Error initializing EvReflection Bool

1

I have a class:

class Ingrediente: EVNetworkingObject 
{
    var idIngrediente:NSNumber!
    var nomeIngrediente:String!
    var adicional:Bool!
    var valorAdicional:NSNumber!
    var empresa:NSNumber!
}

This class receives data from WebService , however I'm having problems with serializar data, only the additional field is not serializando ?

The incoming data:

{"adicional":false,"empresa":500,"idIngrediente":508,"nomeIngrediente":"Ketchup"}

I do this to convert:

let ing = Ingrediente(json:json)

I have 3 more fields using bool and have the same problem, how can I resolve ?

    
asked by anonymous 23.03.2017 / 16:30

2 answers

2

I do not understand anything about EvReflection, but I can help you serialize your json using Swift JSONSerialization's native API to convert json data:

First you should get used to always using structs instead of classes if you are 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 your properties. Always start with let when you declare 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"
}
    
24.03.2017 / 01:40
0

The solution passed by git was to initialize Bool

class Ingrediente: EVNetworkingObject {
var idIngrediente:NSNumber!
var nomeIngrediente:String!
var adicional:Bool = false
var valorAdicional:NSNumber!
var empresa:NSNumber!}

In this way, when serializing the object already changes the value to the correct

    
24.03.2017 / 03:24