JSON encoding with backslashes
Lots of people have problems distinguishing between what they get and what their system prints. So first step is you need to find out what exactly you are receiving, and whether or not these escape characters are just an artefact of you printing.
If this is what you actually receive, then the server has sent you a dictionary with a single key "d" and a string, and the string contains serialized data. In that case, convert the string to NSData and shove it into NSJSONSerialization, which will turn it into the dictionary that you want. This is a rather stupid way to transmit JSON data, but it happens.
// This Dropbox url is a link to your JSON
// I'm using NSData because testing in Playground
if let data = NSData(contentsOfURL: NSURL(string: "https://www.dropbox.com/s/9ycsy0pq2iwgy0e/test.json?dl=1")!) {
var error: NSError?
var response: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error)
if let dict = response as? NSDictionary {
if let key = dict["d"] as? String {
let strData = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var error: NSError?
var response: AnyObject? = NSJSONSerialization.JSONObjectWithData(strData!, options: NSJSONReadingOptions.allZeros, error: &error)
if let decoded = response as? NSDictionary {
println(decoded["IsSuccess"]!) // => 1
}
}
}
}
I guess you have to decode twice: the wrapping object, and its content.
@ericd comments helped me to solve the issue. I accepted his answer for this question. Since I am using Alamofire for asynchronous operation, and SwiftyJSON, I couldn't use his code. Here is the code with Alamofire and SwiftyJSON.
Alamofire.request(.POST, url, parameters: param, encoding: .JSON)
.responseJSON { (req, res, json, error) in
if(error != nil) {
NSLog("Error: \(error)")
failure(res, json, error)
}
else {
var jsond = JSON(json!)
var data = jsond["d"].stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
jsond = JSON(data: data!)