ObjectMapper 在 Swift 中返回 NIL

ObjectMapper returrning NIL in Swift

我正在尝试使用对象映射器 https://github.com/Hearst-DD/ObjectMapper 将 JSON 字符串转换为 Swift 对象。请注意,我在这里将对象简化为单个字段 - 显然我的真实响应有更多字段!

我的回复是:

data arrray response [{
chat =     {
    "_id" = 1;
}}]

所以我想转换为我的聊天 class:

public class Chat: Mappable {
var _id: String? }
public required init?(map: Map){     
}
public func mapping(map: Map) {
    _id <- map["_id"]
}
}

所以我将我的数据数组转换为字典

let jsonResponse = dataArray [0]
let discResponse = jsonResponse as! Dictionary<String,AnyObject>

我什至可以手动访问我的字段

let chat = discResponse["chat"]
let id = chat!["_id"]
print ("CHAT ID", id)

但是映射到对象

let jsonData = try! JSONSerialization.data(withJSONObject: chat, options: .prettyPrinted)

let user = Chat(JSONString: String( describing: jsonData))

returns 无

为什么?

只是把我的评论作为答案,如果有人会坚持同样的问题:使用 Mapper<Chat>().map(JSONObject: chat)。它应该对您的事业有所帮助。