【发布时间】:2018-05-09 03:36:55
【问题描述】:
我正在尝试使用对象映射器https://github.com/Hearst-DD/ObjectMapper 将 JSON 字符串转换为 Swift 对象。请注意,我在这里将对象简化为单个字段 - 显然我的真实响应有更多字段!
我的回答是:
data arrray response [{
chat = {
"_id" = 1;
}}]
所以我想转换为我的聊天类:
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))
返回零
为什么?
【问题讨论】:
-
什么是
jsonData?并且不要滥用String( describing初始化程序。考虑_id也可能是Int。 -
让 jsonData = 试试! JSONSerialization.data(withJSONObject:聊天,选项:.prettyPrinted)
-
_id 是一个字母数字字符串
-
使用映射器
().map(JSONObject: chat) -
@Luzo 如果您将您的评论作为答案,我可以接受,谢谢我查看了文档并没有看到 JSONObject 构造函数(它不存在?)但这解决了谢谢
标签: json swift objectmapper