Search code examples
jsonswiftobjectmapper

ObjectMapper returrning NIL in Swift


I'm trying to use Object mapper https://github.com/Hearst-DD/ObjectMapper to convert a JSON string into a Swift object. Note I've simplified the object to a single field here - obviously my real response has more fields!

My response is:

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

So I want to convert to my chat class:

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

So I convert my data array to a dictionary

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

I can even access my field manually

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

But mapping to the object

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

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

returns nil

Why?


Solution

  • Just putting my comment as an answer, if someone will stuck on the same issue: use Mapper<Chat>().map(JSONObject: chat). It should help your cause.