我使用ObjectMapper将JSON映射到Swift对象。
我有以下Swift对象:
class User: Mappable {
var name: String?
var val: Int?
required init?(map: Map) { }
func mapping(map: Map) {
name <- map["name"]
val <- map["userId"]
}
}我有一个JSON结构:
{
"name": "first",
"userId": "1" // here is `String` type.
},
{
"name": "second",
"userId": 1 // here is `Int` type.
}映射JSON后,userId of User ( name为"first" )为null。
如何将Int/String映射到Int
发布于 2017-07-27 03:00:24
在阅读了ObjectMapper的代码之后,我找到了一种更容易解决问题的方法,就是定制转换。
public class IntTransform: TransformType {
public typealias Object = Int
public typealias JSON = Any?
public init() {}
public func transformFromJSON(_ value: Any?) -> Int? {
var result: Int?
guard let json = value else {
return result
}
if json is Int {
result = (json as! Int)
}
if json is String {
result = Int(json as! String)
}
return result
}
public func transformToJSON(_ value: Int?) -> Any?? {
guard let object = value else {
return nil
}
return String(object)
}
}然后,使用对mapping函数的自定义转换。
class User: Mappable {
var name: String?
var userId: Int?
required init?(map: Map) { }
func mapping(map: Map) {
name <- map["name"]
userId <- (map["userId"], IntTransform()) // here use the custom transform.
}
}希望它能帮助那些有同样问题的人。:)
https://stackoverflow.com/questions/45330913
复制相似问题