2017-11-25 49 views
0

我想使用对象映射器https://github.com/Hearst-DD/ObjectMapper将JSON字符串转换为Swift对象。注意我将对象简化为单个字段 - 显然,我的真实回应有更多的字段!ObjectMapper返回在Swift中的NULL

我的回答是:

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)) 

返回nil

为什么?

+0

什么是'jsonData'?不要误用'String(描述'初始化器,考虑'_id'也可以是'Int'。 – vadian

+0

让jsonData = try!JSONSerialization.data(withJSONObject:chat,options:.prettyPrinted) – stevenpcurtis

+0

_id是一个字母数字字符串 – stevenpcurtis

回答

2

只要将我的评论作为答案,如果有人会卡住同一问题:使用Mapper<Chat>().map(JSONObject: chat)。它应该有助于你的事业。

相关问题