iosdv
iosdv

Reputation: 38

add InvoicID new key and value in json data

here is my json data http://pastie.org/10988178 i want to add invoice id in particular item.like if one invoice have 3 item item than each item array add particular InvoiceID

"ItemDetails":[
{
"ItemId":1,
"ItemType":1,
"InvoiceDetailId":1,
"UPC":"UPCCODE1",
"SKU":"Item 1",
"Description":"Item Description",
"Qty":12,
"PunchListPart":"Item Part New if return item",
"Comment":"Comment1",
"BarCode":""
"InvoiceId":95
},

i want like this output

here is my code but not work

NSLog(@"item=%lu",[[ret_val valueForKey:@"ItemDetails" ] count]);
    NSArray *testarray=[ret_val valueForKey:@"ItemDetails" ];
    NSMutableArray *item=[[NSMutableArray alloc]init];
    for(int i=0; i<[[ret_val valueForKey:@"ItemDetails" ] count]; i++) {

        NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:testarray[i]];
        [dictValues setValue:[[ret_val objectForKey:@"InvoiceId"] objectAtIndex:i] forKey:@"InvoiceId"];
        [item addObject:dictValues];
    }
    NSLog(@"item=%@",item);

ret_val is my NSMutableDictionary in all json data.

Upvotes: 0

Views: 45

Answers (2)

Nirav D
Nirav D

Reputation: 72410

The problem is that ret_val is your root JSON Dictionary and you want InvoiceId that is inside the data Array of your ret_val dictionary. So you need to access it with the dataArray also you can reduce your code using for each loop.

NSMutableArray *items = [[NSMutableArray alloc] init];
NSArray *dataArray = [ret_val objectForKey:@"data"];
for (NSDictionary *dic in dataArray) {
     //Now loop through the `ItemDetails` array.
     NSArray *itemDetails = [dic objectForKey:@"ItemDetails"];
     for (NSDictionary *itemDic in itemDetails) {
          NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:itemDic];
          [dictValues setValue:[dic objectForKey:@"InvoiceId"] forKey:@"InvoiceId"];
          [items addObject:dictValues];
     }
}
NSLog(@"%@", items)

Upvotes: 1

Kundan
Kundan

Reputation: 3082

As it looks like you are getting exception, put a check in Nirav Code as shown below.

if([NSNull null] != [dic objectForKey:@"ItemDetails"])

NSDictionary do not allow values to be nil, hence they are stored as null. Thats why i am suggesting for a null check.

Hope it works.

Upvotes: 0

Related Questions