Kri*_*son 13 cocoa json ios nsjsonserialization
我有一个iOS应用程序需要处理来自Web服务的响应.响应是包含序列化JSON对象的序列化JSON字符串,如下所示:
"{ \"name\" : \"Bob\", \"age\" : 21 }"
Run Code Online (Sandbox Code Playgroud)
请注意,此响应是JSON 字符串,而不是JSON对象.我需要做的是反序列化字符串,以便我得到这个:
{ "name" : "Bob", "age" : 21 }
Run Code Online (Sandbox Code Playgroud)
然后我可以用+[NSJSONSerialization JSONObjectWithData:options:error:]它将其反序列化为一个NSDictionary.
但是,我该如何做到第一步呢?也就是说,我如何"unescape"字符串,以便我有一个序列化的JSON对象? +[NSJSONSerialization JSONObjectWithData:options:error:]仅当顶级对象是数组或字典时才有效; 它不适用于字符串.
我最终编写了自己的JSON字符串解析器,我希望它符合RFC 4627的2.5节.但我怀疑我忽略了一些简单的方法来使用NSJSONSerialization或其他一些可用的方法.
Mar*_*n R 24
如果你有嵌套的JSON,那么只需调用JSONObjectWithData两次:
NSString *string = @"\"{ \\\"name\\\" : \\\"Bob\\\", \\\"age\\\" : 21 }\"";
// --> the string
// "{ \"name\" : \"Bob\", \"age\" : 21 }"
NSError *error;
NSString *outerJson = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingAllowFragments error:&error];
// --> the string
// { "name" : "Bob", "age" : 21 }
NSDictionary *innerJson = [NSJSONSerialization JSONObjectWithData:[outerJson dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
// --> the dictionary
// { age = 21; name = Bob; }
Run Code Online (Sandbox Code Playgroud)