Question

How do I prevent NSJSONSerialization from adding extra backslashes to my URL strings?

NSDictionary *info = @{@"myURL":@"http://www.example.com/test"};
NSData data = [NSJSONSerialization dataWithJSONObject:info options:0 error:NULL];
NSString *string = [[NSString alloc] initWithData:policyData encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);//{"myURL":"http:\/\/www.example.com\/test"}

I can strip the backslashes and use that string but I would like to skip that step if possible...

Was it helpful?

Solution 2

Yeah, this is quite irritating and even more so because it seems there's no "quick" fix to this (i.e. for NSJSONSerialization)

source:
http://www.blogosfera.co.uk/2013/04/nsjsonserialization-serialization-of-a-string-containing-forward-slashes-and-html-is-escaped-incorrectly/
or
NSJSONSerialization serialization of a string containing forward slashes / and HTML is escaped incorrectly


(just shooting in the dark here so bear with me)
If, you're making your own JSON then simply make an NSData object out of a string and send it to the server.
No need to go via NSJSONSerialization.

Something like:

NSString *strPolicy = [info description];
NSData *policyData = [strPolicy dataUsingEncoding:NSUTF8StringEncoding];

i know it won't be so simple but... hm... anyways

OTHER TIPS

This worked for me

NSDictionary *policy = ....;
NSData *policyData = [NSJSONSerialization dataWithJSONObject:policy options:kNilOptions error:&error];
if(!policyData && error){
    NSLog(@"Error creating JSON: %@", [error localizedDescription]);
    return;
}

//NSJSONSerialization converts a URL string from http://... to http:\/\/... remove the extra escapes
policyStr = [[NSString alloc] initWithData:policyData encoding:NSUTF8StringEncoding];
policyStr = [policyStr stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
policyData = [policyStr dataUsingEncoding:NSUTF8StringEncoding];

If your target is >= iOS 13.0, then just add .withoutEscapingSlashes to the options.

Example:

let data = try JSONSerialization.data(withJSONObject: someJSONObject, options: [.prettyPrinted, .withoutEscapingSlashes])

print(String(data: data, encoding: String.Encoding.utf8) ?? "")

I have tracked this issue for many years, and it is still not fixed. I believe Apple will never fix it for legacy reasons (it will break stuff).

The solution in Swift 4.2:

let fixedString = string.replacingOccurrences(of: "\\/", with: "/")

It will replace all \/ with /, and is safe to do so.

I had this issue and resolved it by instead using the now available JSONEncoder. Illustrated with code:

struct Foozy: Codable {
    let issueString = "Hi \\ lol lol"
}

let foozy = Foozy()

// crashy line
//let json = try JSONSerialization.data(withJSONObject: foozy, options: [])

// working line
let json = try JSONEncoder().encode(foozy)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top