原文链接:https://segmentfault.com/q/1010000000576646/revision
iOS中使用NSJSONSerialization
把对象转为JSON字符串后,多出来反斜杠的问题
代码
NSDictionary *dic = @{@"url": @"http://..."};
NSLog(@"%@", dic);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(@"%@, json object = %@", jsonString, jsonDict);
执行结果:
2016-12-15 16:49:45.009 test[14989:546596] {
url = "http://...";
}
2016-12-15 16:49:45.010 test[14989:546596] {"url":"http:\/\/..."}, json object = {
url = "http://...";
}
转换后的json字符串中url地址被转义了 :(
使用字符串替换可以事后弥补:
[jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
如何事先预防呢?
------------------------------------------------------
这里:https://segmentfault.com/q/1010000000576646尝试给出了答案
苹果就是这么任性手动替换一下吧类似:
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];
参见:
how to prevent NSJSONSerialization from adding extra escapes in URL
NSJSONSerialization serialization of a string containing forward slashes / and HTML is escaped incorrectly
-------------------------------------------------------
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"];
最后,顺便看一下http头部 application/json 和 text/json 的区别
这篇文章:http://www.tuicool.com/articles/F7ziaa
标准写法的 application/json,人们有时候也习惯text/json,但是text/json不兼容的,建议你用标准application/json
服务端 向 客户端 发送 JSON数据 时:
Content-Type = 'application/json;charset=UTF-8'
服务端 向 客户端 发送 JS 代码 时:
Content-Type = 'text/javascript;charset=UTF-8'
服务端 判断 客户端 提交的是否是 JSON数据 时 :
Content-Type = 'application/json;charset=UTF-8'
Content-Type = 'text/json;charset=UTF-8'
Content-Type = 'text/javascript;charset=UTF-8'
Content-Type = 'application/javascript;charset=UTF-8'
只要 Content-Type 满足上面4个条件中的 任意一个时,就可以认为提交的数据是 JSON数据