我正在使用 http 服务器,它在响应正文中返回 JSON 字符串:
"Some text.\nSome text.\n\t\"Some text in quotes.\""
我需要删除字符串开头和结尾的引号,并且需要取消转义特殊符号。我为 NSString 创建了类别,但我认为这是错误的实现:https://gist.github.com/virasio/59907e087f859e6c1723 我有别的想法。我可以使用 NSJSONSerialization:
NSString *sourceString = @"\"Some text.\\nSome text.\\n\\t\\\"Some text in quotes.\\\"\"";
NSString *jsonObject = [NSString stringWithFormat:@"{ \"value\" : %@ }", sourceString];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:[jsonObject dataUsingEncoding:NSUTF8StringEncoding options:0 error:NULL]];
NSString *result = [object objectForKey:@"value"];
但是……也不好。
最佳答案
默认情况下,Foundation 只会解析 JSON 对象或数组,但如果您告诉它接受 JSON 片段,它可以解析字符串、数字和 bool 值:
NSData *data = [@"\"Some text.\\nSome text.\\n\\t\\\"Some text in quotes.\\\"\""
dataUsingEncoding:NSUTF8StringEncoding];
id result = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:NULL];
NSLog(@"[result class] = %@", [result class]);
NSLog(@"result = %@", result);
产量:
[result class] = __NSCFString result = Some text. Some text. "Some text in quotes."
这实际上是传递 error
真正有用的情况之一。我曾尝试过不传递 NSJSONReadingAllowFragments
并收到一条非常明确的错误消息:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)
关于ios - 如何将转义的 JSON 字符串转换为 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23998139/