首页 > 解决方案 > 如何使用objective-c检查JSON的结构

问题描述

我有一个结构为字典数组的 JSON。

正常的结构会是这样的,(在解析成数组之后):

[0] - [NSDictionary *] 3 key/value pairs
   [0] departure - 1 element
      -> key @"city"
      -> value @"New York"
   [1] arrival -1 element
      -> key @"city"
      -> value @"Atlanta" 
   [2] bus -3 key/values pairs
      -> key @"bus"
      -> value (NSDictionary *) 3 key/value pairs 
            [0] @"number" (long) 123 
            [1] @"driver" @"smith"
            [2] @"type" @"40 seat coach"

但是,如果您解析具有结构但缺少一个关键元素(即最后一个元素)的“坏”JSON

[0] - [NSDictionary *] 3 key/value pairs
   [0] departure - 1 element
      -> key @"city"
      -> value @"New York"
   [1] arrival -1 element
      -> key @"city"
      -> value @"Atlanta" 
   [2] bus -3 key/values pairs
      -> key @"bus"
      -> value (NSNull *)  0x8976656
            -> NSObject

如果我尝试在公共汽车下查询司机的姓名,它会崩溃。我试图测试 null 但不起作用。它在请求期间也不会抛出错误(NSURLSessionDataTask)。你如何防范这种情况?

NSArray *busCompany = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];

myBuses =[[NSMutableDictionary]alloc]init];

for (NSDictionary *companiesDict in busCompany) {
   myBuses = companiesDict[@"bus"];
   if(myBuses) {        //also tried if(myBuses != NULL)
       NSString *driverName = [myBuses ForKey: @"driver"];
    }
}

它给了我[NSNULL objectforkey]错误。

标签: jsonobjective-cxcode

解决方案


推荐阅读