how to prevent NSJSONSerialization from adding extra escapes in URL

前端 未结 5 702

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

NSDictionary *info = @{@\"myURL\":@\"http://www.example.com/test\"};
NS         


        
相关标签:
5条回答
  • 2020-11-29 09:38

    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) ?? "")
    
    0 讨论(0)
  • 2020-11-29 09:44

    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.

    0 讨论(0)
  • 2020-11-29 09:45

    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];
    
    0 讨论(0)
  • 2020-11-29 09:46

    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)
    
    0 讨论(0)
  • 2020-11-29 09:49

    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

    0 讨论(0)
提交回复
热议问题