Objectmapper: Cast String to Bool

Created on 12 May 2017  ·  2Comments  ·  Source: tristanhimmelman/ObjectMapper

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

Most helpful comment

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)

All 2 comments

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)

Thanks @chenkefeng. Thats the correct approach 👍

Was this page helpful?
0 / 5 - 0 ratings