ios - 如何将转义的 JSON 字符串转换为 NSString?

标签 ios objective-c json

我正在使用 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/

相关文章:

mysql - 理解 xcode json 网络请求

c# - Json 转换空字符串而不是 null

json - 根据某些条件排除 json 中的字段

ios - iOS ScrollView 中的多个 View

objective-c - 检测系统音量何时在 mac 上发生变化?

objective-c - Apple 的 Reachability 文件中的奇怪错误

iphone - EGOTableViewPullRefresh 的问题 - 没有改变?

ios - 带有固定部分标题的 UITableView

ios - 如何在 native Google Drive iOS 应用程序中打开文档?

android - Flutter/Dart 静态变量丢失/不断重新初始化