Search code examples
iosswiftjsonserializer

JSONSerialization.jsonObject returns nil


var responseString = String(data: data, encoding: .utf8)
var responseDict: [AnyHashable : Any]? = nil
if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
   responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [AnyHashable : Any]
}  

responseString is coming out to be :

[{\"message_id\":1916,\"in_app\":{\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-07T23:17:46.169-05:00\",\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"This is what your message will look like! Type in your message in the text area and get a preview right here\",\"data\":{},\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"subtitle\":\"\"}},{\"message_id\":1920,\"in_app\":{\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-08T03:52:15.404-05:00\",\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"This is what your message will look like! Type in your message in the text area and get a preview right here\",\"data\":{},\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"subtitle\":\"\"}}]

responseDict is coming out to be nil.
The corresponding Objective-C code was working just fine.


Solution

  • This works fine…

    let json = """
    [{\"message_id\":1916,\"in_app\":{\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-07T23:17:46.169-05:00\",\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"This is what your message will look like! Type in your message in the text area and get a preview right here\",\"data\":{},\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"subtitle\":\"\"}},{\"message_id\":1920,\"in_app\":{\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-08T03:52:15.404-05:00\",\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"This is what your message will look like! Type in your message in the text area and get a preview right here\",\"data\":{},\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"subtitle\":\"\"}}]
    """.data(using: .utf8)!
    
    do {
        let object = try JSONSerialization.jsonObject(with: json, options: [])
        print(object)
    } catch {
        print(error)
    }
    

    … but don't use JSONSerialization… declare custom objects that represent your data and use Decodable instead