Iphone 当我们从ios中的json中获取valueOfKey时,如何检查它是数组还是对象
我有两个案例需要解析Iphone 当我们从ios中的json中获取valueOfKey时,如何检查它是数组还是对象,iphone,objective-c,ios,xcode,Iphone,Objective C,Ios,Xcode,我有两个案例需要解析JSON首先是: { "post_filter_data": { "Items": [ { "ItemID": "50cb4e46b5d30b0002000009", "ItemName": "Fruit salad test", "ItemPrice": "122.0", "ItemDescripti
JSON
首先是:
{
"post_filter_data": {
"Items": [
{
"ItemID": "50cb4e46b5d30b0002000009",
"ItemName": "Fruit salad test",
"ItemPrice": "122.0",
"ItemDescription": "test test",
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50cb4e64b5d30b0002000013/landing_page.jpg?1355501156"
},
{
"ItemID": "50d0870d910ef2000200000a",
"ItemName": "test new",
"ItemPrice": "120.0",
"ItemDescription": null,
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50d0871a910ef20002000015/Screenshot-2.png?1355843354"
}
]
}
}
其中Items是一个NSArray
,它很容易解析,但当只有一个对象通过异常得到它时。
第二个JSON
是其中的Items标记有一个对象:
{
"post_filter_data": {
"Items": {
"ItemID": "50d1e9cd9cfbd20002000016",
"ItemName": "test",
"ItemPrice": "120.0",
"ItemDescription": "test",
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50d1ea019cfbd20002000022/11949941671787360471rightarrow.svg.med.png?1355934209"
}
}
}
我的代码就是在这里解析的:
NSDictionary *dictMenu=[responseDict valueForKey:@"post_filter_data"];
NSArray* subMenuArray=[dictMenu valueForKey:@"Items"];
我有没有办法检查
valueForKey:@“Items”
是Array
还是Object
是的,您可以使用类
进行检查
if ([[dictMenu valueForKey:@"Items"] isKindOfClass:[NSArray class]])
{
// array inside
}
获取接收数据中的数据rx,然后检查对象的类
id object = [NSJSONSerialization
JSONObjectWithData:_recievedData
options:kNilOptions
error:&error];
if (error)
{
NSLog(@"Error in rx data:%@",[error description]);
}
if([object isKindOfClass:[NSString class]] == YES)
{
NSLog(@"String rx from server");
}
else if ([object isKindOfClass:[NSDictionary class]] == YES)
{
NSLog(@"Dictionary rx from server");
}
else if ([object isKindOfClass:[NSArray class]] == YES)
{
NSLog(@"Array rx from server");
}
你从哪里得到这个json?你能控制它吗?我会考虑更改JSON本身来发送一个数组,即使其中包含一个对象。当然,您可以检查类型,因为下面的答案描述了如何。。