如何使用NSJSONSerialization反序列化转义的JSON字符串? [英] How can you deserialize an escaped JSON string with NSJSONSerialization?
问题描述
我有一个iOS应用程式需要处理来自网路服务的回应。响应是包含序列化JSON对象的序列化JSON字符串,如下所示:
I have an iOS app that needs to process a response from a web service. The response is a serialized JSON string containing a serialized JSON object, looking something like this:
"{ \"name\" : \"Bob\", \"age\" : 21 }"
请注意,此响应是JSON 字符串,而不是JSON对象。我需要做的是反序列化字符串,所以我得到这个:
Note that this response is a JSON string, not a JSON object. What I need to do is deserialize the string, so that I get this:
{ "name" : "Bob", "age" : 21 }
然后我可以使用 + [NSJSONSerialization JSONObjectWithData:选项:错误:]
将反序列化为 NSDictionary
。
And then I can use +[NSJSONSerialization JSONObjectWithData:options:error:]
to deserialize that into an NSDictionary
.
我做第一步?也就是说,如何unescape字符串,使我有一个序列化的JSON对象? + [NSJSONSerialization JSONObjectWithData:options:error:]
仅在顶层对象是数组或字典时有效;它不适用于字符串。
But, how do I do that first step? That is, how to I "unescape" the string so that I have a serialized JSON object? +[NSJSONSerialization JSONObjectWithData:options:error:]
only works if the top-level object is an array or a dictionary; it doesn't work on strings.
我最后写了我自己的JSON字符串解析器,我希望符合 RFC 4627的第2.5节。但我怀疑我忽略了一些简单的方法来使用 NSJSONSerialization
或一些其他可用的方法。
I ended up writing my own JSON string parser, which I hope conforms to section 2.5 of RFC 4627. But I suspect I've overlooked some easy way to do this using NSJSONSerialization
or some other available method.
推荐答案
如果您有嵌套JSON,则只需调用 JSONObjectWithData
两次:
If you have nested JSON, then just call JSONObjectWithData
twice:
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; }
这篇关于如何使用NSJSONSerialization反序列化转义的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!