我有2個案例分析JSON
首先是:如何檢查valueOfKey是數組或對象時,我們把它從JSON在IOS
{
"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"
}
]
}
}
中哪些項目是NSArray
,它的解析很容易,但如果只有一個對象我通過例外得到它。 二JSON
是在項目標記有一個一個對象:
{
"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
。
你從哪裏得到這個json?你有控制它嗎?我會考慮將json本身改爲始終發送一個數組,即使只有一個對象。當然你可以檢查類型,下面的答案描述如何.. –