今天检查部门其他小伙伴的代码时,发现他写的解析JSON有一些问题,导致了闪退,他把解析后的数据直接拿来用,类型不对导致闪退,故自己也记录一下。
1、调用方法:
/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
*/
+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
注释的几个理解:
顶级对象:
- 默认情况下,JSON 解析器只接受顶级对象是
NSArray
或NSDictionary
。如果顶级对象是其他类型,如字符串(NSString
)或数字(NSNumber
),解析器会抛出错误。 - 使用
NSJSONReadingAllowFragments
选项时,解析器将允许顶级对象是这些非标准类型的 JSON 片段。
2、该方法的return的类型是 id,但是他在解析没有报错的时候会解析为 NSArray 或者NSDictionary,为了把代码写健硕,防止出现问题,这块代码解析时应该这样写:
NSString *jsonString = @"\"a string value\""; // 非标准 JSON 顶级片段
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
// 使用 NSJSONReadingAllowFragments 选项来允许顶级片段
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (error) {
NSLog(@"JSON Parsing Error: %@", error.localizedDescription);
} else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSLog(@"Parsed NSDictionary: %@", jsonObject);
} else if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(@"Parsed NSArray: %@", jsonObject);
} else {
NSLog(@"Parsed object is of an unexpected type.");
}