如何防止NSJSONSerialization向我的URL字符串添加额外的反斜杠?
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"}我可以去掉反斜杠并使用字符串,但如果可能的话,我想跳过这一步.
发布于 2013-10-29 06:35:11
是的,这很让人恼火,甚至更令人恼火,因为它似乎没有“快速”的解决办法(即对于NSJSONSerialization)。
来源:
或
(只是在黑暗中拍摄,所以请容忍我)
如果您正在创建自己的JSON,那么只需使用字符串创建一个NSData对象并将其发送到服务器。
不需要经过NSJSONSerialization。
类似于:
NSString *strPolicy = [info description];
NSData *policyData = [strPolicy dataUsingEncoding:NSUTF8StringEncoding];我知道事情不会这么简单但是..。嗯..。不管怎样,
发布于 2014-07-17 15:09:43
这对我来说很管用
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];发布于 2020-01-20 19:42:17
如果目标是>= iOS 13.0,那么只需将.withoutEscapingSlashes添加到选项中即可。
示例:
let data = try JSONSerialization.data(withJSONObject: someJSONObject, options: [.prettyPrinted, .withoutEscapingSlashes])
print(String(data: data, encoding: String.Encoding.utf8) ?? "")https://stackoverflow.com/questions/19651009
复制相似问题