JSON encoding with backslashes

Meanteacher picture Meanteacher · Mar 23, 2015 · Viewed 15k times · Source

I m using Alamofire and SwiftyJSOn to parse JSON output. It works very well however some sites give json with escaped output. I use Alamofire like below

    Alamofire.request(.POST, url, parameters: param, encoding: .JSON)
        .responseJSON { (req, res, json, error) in
         var json = JSON(json!)

Site gives me JSON result with escaped string so SwiftyJSON can't decode it. How can I convert below

{
    "d": "{\"UniqeView\":{\"ArrivalDate\":null,\"ArrivalUnitId\":null,\"DeliveryCityName\":null,\"DeliveryTownName\":null},\"ErrorMessage\":null,\"Message\":null,\"IsFound\":false,\"IsSuccess\":true}"
}

to something like

{
       "d": {
          "UniqeView": {
             "ArrivalDate": null,
             "ArrivalUnitId": null,
             "DeliveryCityName": null,
             "DeliveryTownName": null
          },
          "ErrorMessage": null,
          "Message": null,
          "IsFound": false,
          "IsSuccess": true
       }
    }

Answer

Eric Aya picture Eric Aya · Mar 23, 2015
// 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.