4

我有2个案例要解析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"Arrayor Object

4

2 回答 2

11

在 _recievedData 中获取数据 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");
    }
于 2012-12-20T09:11:02.223 回答
8

是的,您可以使用classlike

if ([[dictMenu valueForKey:@"Items"] isKindOfClass:[NSArray class]])
{
    // array inside
}
于 2012-12-20T09:02:29.213 回答