how to prevent NSJSONSerialization from adding extra escapes in URL

荒凉一梦 提交于 2019-11-26 12:29:27

问题


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


回答1:


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




回答2:


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];



回答3:


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.



来源:https://stackoverflow.com/questions/19651009/how-to-prevent-nsjsonserialization-from-adding-extra-escapes-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!