iOS Objective-c解析JSON注意事项

今天检查部门其他小伙伴的代码时,发现他写的解析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 解析器只接受顶级对象是 NSArrayNSDictionary。如果顶级对象是其他类型,如字符串(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.");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值