Objective c 如何防止NSJSONSerialization在URL中添加额外转义

Objective c 如何防止NSJSONSerialization在URL中添加额外转义,objective-c,nsjsonserialization,Objective C,Nsjsonserialization,如何防止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 enc

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

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

是的,这非常令人恼火,甚至更令人恼火,因为似乎没有“快速”解决方法(即NSJSONSerialization)

来源:



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

比如:

NSString *strPolicy = [info description];
NSData *policyData = [strPolicy dataUsingEncoding:NSUTF8StringEncoding];
我知道事情不会这么简单但是。。。陛下无论如何,这对我来说很有效

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

我已经跟踪这个问题很多年了,但它仍然没有得到解决。我相信苹果永远不会因为遗留的原因修复它(它会破坏东西)

Swift 4.2中的解决方案:

let fixedString = string.replacingOccurrences(of: "\\/", with: "/")

它将用
/
替换所有
\/
,这样做是安全的。

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

struct Foozy:Codable{
让issueString=“Hi\\lol-lol”
}
让foozy=foozy()
//粗线条
//让json=try JSONSerialization.data(使用jsonObject:foozy,选项:[])
//工作线
让json=try JSONEncoder().encode(foozy)

如果您的目标是>=iOS 13.0,则只需在选项中添加.WithouteScapingsFlash即可

例如:

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

print(String(data: data, encoding: String.Encoding.utf8) ?? "")

谢谢你的链接。至于在黑暗中拍摄,如果我手动构建json字符串,我会这样做,但我使用NSJSONSerialization使构建字符串更容易。以上只是一个简单的问题的例子。是的,考虑到更多的变量和参数,我可以理解NSJSON系列化更容易。无论如何,如果我找到了解决方案,我会记得在这里发帖。最后,我还为这一个案例手动构建了JSON,在所有其他案例中,我都使用JSONSerializer。如果应用程序可能会删除这些字符的有效匹配项(可能它们会在Base64编码中自然出现),你不喜欢让应用程序重新检查并替换字符串。你找到了解决方案吗?下面是我关于
AFJSONRequestSerializer
的一个类别的答案,基于joel的方法:如果有人在调试器中看到这一点,那么很可能不是您所认为的。在显示和打印字符串时,lldb将转义字符串中的某些字符。要进行测试,请不要执行
po
do
po print()
。我的生命中有三个小时都被那个怪事夺走了。“\”实际上不在那里…@b真的…而你,先生,是一个目光冷酷的导弹人。你刚才救了我3个小时。非常感谢。这会损坏像\/\/smileys这样的字符串。“这是一个反斜杠,后跟斜杠:\\/”将被替换为“这是一个反斜杠,后跟\/”,这不是任何人想要的。@LevWalkin“\/\/”微笑将被编码为“\\/\/”,在将“\/”替换为“/”之后,它将再次被“\/\/”替换