【问题标题】:ObjectMapper returrning NIL in SwiftObjectMapper 在 Swift 中返回 NIL
【发布时间】: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


【解决方案1】:

如果有人会坚持同样的问题,请将我的评论作为答案:使用Mapper&lt;Chat&gt;().map(JSONObject: chat)。它应该对您的事业有所帮助。

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 2023-03-21
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多