Search code examples
iosnsmutablearraynsmutabledictionary

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.


Solution

  • 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)