代码
NSDictionary *dic = @{@"url": @"http://..."};
NSLog(@"%@", dic);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
执行结果:
2014-06-12 14:44:19.427 main[64877:1322484] {
url = "http://...";
}
2014-06-12 14:44:19.429 main[64877:1322484] {
"url" : "http:\/\/..."
}
转换后的json字符串中url地址被转义了 :(
使用字符串替换可以事后弥补:
[jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
如何事先预防呢?
PS:在和UIWebView进行js调用时需要不转义的json字符串,所以还是希望正面解决掉。
這個不需要做處理的,直接用就是了。
如果直接取出顯示在 Label 上,內部做過轉義的。所以無需理會。
可以參考我寫的部落格《IOS 7 利用系統自備庫進行 POST JSON 非同步存取操作》
關於 json 標準文檔中
是否应该转义成
/
, 我并没细究. 但是很多开源实现 decode 的时候是不会将/
转回的. 因此我並不同意樓上說的觀點, 某些情況下必須要處理, 但我不知道官方NSJSONSerialization的處理方法, 所以改用開源的 jsonkit 繞過了這個問題
蘋果就是這麼任性手動替換一下吧類似:
請見:
how to prevent NSJSONSerialization from adding extra escapes in URL
NSJSONSerialization serialization of a string containing forward slashes / and HTML is escaped incorrectly