问题描述
我有一个 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:options:error:]
将其反序列化为 NSDictionary
.
And then I can use +[NSJSONSerialization JSONObjectWithData:options:error:]
to deserialize that into an NSDictionary
.
但是,我该怎么做第一步呢?也就是说,我如何逃脱"?字符串以便我有一个序列化的 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 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2