Serialize Json String That Contains Escaped (Backslash and Double Quote) Swift Return Badly Formed Object

Serialize JSON string that contains escaped (backslash and double quote) Swift return Badly formed object

First of all if you wrap the JSON in the literal string syntax of Swift 4 you have to escape the backslashes.

let jsonStr = """
{
"status": "success",
"data": "{\\"name\\":\\"asd\\",\\"address\\":\\"Street 1st\\"}"
}
"""

You got nested JSON. The value for key data is another JSON string which must be deserialized separately

let jsonData = Data(jsonStr.utf8)

do {
if let object = try JSONSerialization.jsonObject(with: jsonData) as? [String:String] {
print(object)
if let dataString = object["data"] as? String {
let dataStringData = Data(dataString.utf8)
let dataObject = try JSONSerialization.jsonObject(with: dataStringData) as? [String:String]
print(dataObject)
}
}
} catch {
print(error)
}

Or – with a bit more effort but – much more comfortable with the (De)Codable protocol

struct Response : Decodable {

private enum CodingKeys : String, CodingKey { case status, data }

let status : String
let person : Person

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
status = try container.decode(String.self, forKey: .status)
let dataString = try container.decode(String.self, forKey: .data)
person = try JSONDecoder().decode(Person.self, from: Data(dataString.utf8))
}
}

struct Person : Decodable {
let name, address : String
}

let jsonStr = """
{
"status": "success",
"data": "{\\"name\\":\\"asd\\",\\"address\\":\\"Street 1st\\"}"
}
"""
let jsonData = Data(jsonStr.utf8)

do {
let result = try JSONDecoder().decode(Response.self, from: jsonData)
print(result)
} catch {
print(error)
}

Swift String escaping when serializing to JSON using Codable

For iOS 13+ / macOS 10.15+


You can use .withoutEscapingSlashes option to json decoder to avoid escaping slashes

let user = User(username: "John", profileURL: "http://google.com")

let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .withoutEscapingSlashes
let json = try? jsonEncoder.encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
print(str)
}

Console O/P

{"profileURL":"http://google.com","username":"John"}


NOTE: As mention by Martin R in comments \/ is a valid JSON escape sequence.

JSON encoding with backslashes

// 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.

Why json response includes backward slashes in web api response

You are serializing two times the same object. The first time you are serializing it manually using:

Newtonsoft.Json.JsonConvert.SerializeObject(data)

Then you are returning another object that the framework itself will serialize, this will cause it to escape characters inside the string object called data.

Do not manually serialize your data, let the framework do the heavy lifting:

return new HttpResponseBody(true, message, (int)System.Net.HttpStatusCode.OK, data);

How to escape double quotes in JSON

Try this:

"maingame": {
"day1": {
"text1": "Tag 1",
"text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
}
}

(just one backslash (\) in front of quotes).

How do I handle newlines in JSON?

This is what you want:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

You need to escape the \ in your string (turning it into a double-\), otherwise it will become a newline in the JSON source, not the JSON data.



Related Topics



Leave a reply



Submit