ObjectMapper icon indicating copy to clipboard operation
ObjectMapper copied to clipboard

Cast String to Bool

Open scinfu opened this issue 9 years ago • 2 comments

Why i can't cast a json value string to bool? like "1" or "0" var ABool: Bool? ABool <- map["KEY"]

scinfu avatar May 12 '17 09:05 scinfu

You can do it!

Example

struct User: Mappable {
    
    var name = ""
    var dict = [String:Any]()
    
    var flag = false
    
    init() {}
    
    init?(map: Map) {
        
    }
    
    mutating func mapping(map: Map) {
        name <- map["name"]
        dict <- map["dict"]
        flag <- (map["flag"], TransformOf(fromJSON: { (intVal: Int?) -> Bool? in
            return Bool(NSNumber(value: intVal ?? 0))
        }, toJSON: { (boolVal: Bool?) -> Int? in
            return (boolVal ?? false) ? 1 : 0
        }))
    }
    
}

        let newJsonString = "{\"dict\":{\"key2\":\"value2\",\"key1\":\"value1\"},\"name\":\"test\",\"flag\":1}"
        
        guard let newU = User(JSONString: newJsonString) else {return}
        
        print(newU)
        ////  User(name: "test", dict: ["key2": value2, "key1": value1], flag: true)

chenkefeng avatar May 16 '17 03:05 chenkefeng

Thanks @chenkefeng. Thats the correct approach 👍

tristanhimmelman avatar May 26 '17 15:05 tristanhimmelman