29

如何防止 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"}

我可以去掉反斜杠并使用该字符串,但如果可能的话,我想跳过这一步......

4

5 回答 5

20

这对我有用

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];
于 2014-07-17T15:09:43.067 回答
5

是的,这很烦人,甚至更烦人,因为似乎没有“快速”解决这个问题(即用于 NSJSONSerialization)

来源:
http
://www.blogosfera.co.uk/2013/04/nsjsonserialization-serialization-of-a-string- contains-forward-slashes-and-html-is-escaped-incorrectly/ 或
字符串的NSJSONSerialization序列化包含正斜杠 / 并且 HTML 被错误地转义


(这里只是在黑暗中拍摄,所以请耐心等待)
如果您正在制作自己的 JSON,那么只需从字符串中制作一个 NSData 对象并将其发送到服务器。
无需通过 NSJSONSerialization。

就像是:

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

我知道这不会那么简单,但是……嗯……无论如何

于 2013-10-29T06:35:11.337 回答
3

如果您的目标是 >= iOS 13.0,那么只需将 .withoutEscapingSlashes 添加到选项中。

例子:

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

print(String(data: data, encoding: String.Encoding.utf8) ?? "")
于 2020-01-20T19:42:17.693 回答
1

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.

于 2019-03-21T12:47:25.637 回答
0

我遇到了这个问题并通过使用现在可用的 JSONEncoder 来解决它。用代码说明:

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)
于 2019-12-12T16:32:19.010 回答