【问题标题】:Using Alamofire and Objectmapper the integer value always zero使用 Alamofire 和 Objectmapper 整数值始终为零
【发布时间】:2016-05-09 03:49:39
【问题描述】:

我将 Alamofire 与 ObjectMapper 一起使用,我的模型类就是这样

class Category: Object, Mappable {

dynamic var id: Int = 0
dynamic var name = ""
dynamic var thumbnail = ""
var children = List<Category>()


override static func primaryKey() -> String? {
    return "id"
}


required convenience init?(_ map: Map) {
    self.init()
}

func mapping(map: Map) {
    id <- map["id"]
    name <- map["name"]
    thumbnail <- map["thumbnail"]
    children <- map["children"]
}

}

我正在使用这样的 Alamofire

 Alamofire.request(.GET, url).responseArray { (response: Response<[Category], NSError>) in

        let categories = response.result.value

        if let categories = categories {
            for category in categories {
                print(category.id)
                print(category.name)
            }
        }
    }

id总是为零,不知道为什么?

【问题讨论】:

  • JSON 文件中是否存在“id”字段?如果没有,您的初始值为零将保持不变。 JSON文件中的引号中的值是什么?如果是,那么它是一个字符串。我不知道 ObjectMapper 是否会将其转换为 Int。
  • 是的“id”存在于 JSON 文件中
  • 如果我删除了可以映射值的引号,那么 JSON 文件中引号中“id”的值是正确的。谢谢@BobWakefield

标签: swift alamofire objectmapper


【解决方案1】:

我通过在模型类的映射函数中添加转换来修复它

id <- (map["id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))

感谢@BobWakefield

【讨论】:

  • 我在答案中添加了我的评论。你能改变正确的答案,让我得到它的功劳吗?谢谢。
  • 我将它用于 json 中的 int 到对象解析中的字符串,但我无法摆脱 Optional()
【解决方案2】:

JSON 文件中是否存在“id”字段?如果没有,您的初始值为零将保持不变。 JSON文件中的引号中的值是什么?如果是,那么它是一个字符串。不知道 ObjectMapper 会不会转成 Int。

将我的评论移至答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多