Swift Escaping Unwanted Backslash Characters on JSON Encoding

Viewed 284

I’m getting a bunch of unneeded “escaped back-slash” characters when I convert my Swift Dictionary object using JSONSerialization. It’s only happening on one of my Key-Value pairs - the one that has a URL in it:

"image" : "http:\/\/www.someWebSite.com\/images/\triangleImage.jpg”

I tried to run JSONSerialization twice thinking it might solve the problem - but it just crashes. Swift is not my main language so I’m not really sure how to fix this?

Here’s my code:

// Creating the Dictionary:
triangleDictionary["name"] = "triangle 01”
triangleDictionary["image"] = "http://www.someWebSite.com/triangleImage.jpg"
triangleDictionary["description"] = "a geometric shape"


// Serializing it to a JSON object:
do {
   let triangleData = try JSONSerialization.data(withJSONObject: triangleDictionary, options: [.prettyPrinted])
   let triangleDataJSONString = String(data: triangleData, encoding: .utf8)!
   print("triangleDataJSONString = \(String(describing: triangleDataJSONString))")
}
catch {
   print("ERROR Serializing triangleData!: \(error)")
}

The output I get is almost perfect - except for those extra back-slashes:

{  
    "name" : “triangle 01”,  
    "description" : “a geometric shape”,
    "image" : "http:\/\/www.someWebSite.com\/images/\triangleImage.jpg”
}

What do I need to do to fix this?

1 Answers

Add this line in your code

header('Content-Type: application/json');
Related