我有以下JSON响应,它已存储在NSMutableDictonary
中。我想添加 special_item 的所有价格。
{
"order_id": "1",
"order_name": "xyz",
"order_item": [
{
"item_id": "1",
"item_name": "myone",
"special_item": [
{
"s_item_id": "1",
"price": "10"
},
{
"s_item_id": "2",
"price": "100"
}
]
},
{
"item_id": "2",
"item_name": "mytwo",
"special_item": [
{
"s_item_id": "11",
"price": "15"
},
{
"s_item_id": "22",
"price": "110"
}
]
}
]
}
是否可以使用NSPredicate
添加所有价格?或者如何使用NSPredicate
得到所有价格值的数组?(例如:[@ 10,@ 100,@ 15,@ 110])
谢谢!
答案 0 :(得分:2)
这很简单
你可以尝试下面的代码
NSArray *arr = [dix valueForKeyPath:@"order_item.special_item.price"];
long total = 0;
for (id price in arr) {
if ([price isKindOfClass:[NSArray class]]) {
total += [[price valueForKeyPath:@"@sum.self"] longValue];
}
else {
total += [price longValue];
}
}
答案 1 :(得分:0)
NSInteger *total=0;
NSArray *arr=[NSDictionary objectForKey=@"order_item"];
for(NSDictionary *dic in arr){
NSArray *array=[dic objectForKey=@"special_item"];
for(NSDictionary *d in array){
total=total+[[d objectForKey=@"price"] intValue];
}
}
NSLog("Total:- %d",total);