如何使用JSON-Framework在XCode上检测JSON对象/ JSON数组

时间:2010-07-18 18:54:51

标签: iphone json json-framework

我在使用JSON解析时遇到了一些问题。当我点击URL时,我得到了像这样的JSON响应:

//JSON 1
{ "data":
  {"array":
    ["3",
       {"array":
          [
            {"id":"1","message":"Hello","sender":"inot"},
            {"id":"2","message":"World","sender":"inot"},
            {"id":"3","message":"Hi","sender":"marza"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

但是如果数据的结果只是1,则JSON响应是这样的:

//JSON 2
{ "data":
  {"array":
    ["3",
       {"array":
          {"id":"3","message":"Hi","sender":"marza"}
       }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

我实现此代码以获取id,message和sender值,并在JSON 1上正常工作,但在JSON 2上出错。我使用JSON-Framework。问题是如何检测JSON响应是对象({})还是数组([])??

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"id      = %@",[item objectForKey:@"id"]);
   NSLog(@"message = %@",[item objectForKey:@"message"]);
   NSLog(@"sender  = %@",[item objectForKey:@"sender"]);
}

1 个答案:

答案 0 :(得分:15)

您可以使用id并检查您获得的对象是NSArray还是NSDictionary:

id item = [json valueForKeyPath:@"data.array"];
if ([item isKindOfClass:[NSArray class]]) {
    // item is an array
}
else if ([item isKindOfClass:[NSDictionary class]]) {
    // item is a dictionary
}