我知道我们在序列化时通常使用 NSDictionary
或 NSArray
但我想知道如果我们更喜欢 NSDictionary
有什么优势吗?
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
最佳答案
这不是偏好问题。 JSONObjectWithData:
方法返回类型为 id
的对象。
A Foundation object from the JSON data in data, or nil if an error occurs.
所以并不是说你可以选择是要 NSArray
还是 NSDictionary
。事实上,您应该始终进行检查以确保返回的对象是您期望的类型。
您的代码应如下所示:
NSError* error;
id JSONObject = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if ([JSONObject isKindOfClass:[NSDictionary class]])
{
NSDictionary *JSONDictionary = (NSDictionary *)JSONObject;
// Do your stuff.
}
否则,当从您调用的端点返回的 JSON
不再是字典,而是数组或您不期望的任何内容时,您将面临崩溃的风险。
关于ios - 在解析 JSON 时使用 NSDictionary 有什么优势或好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24777210/