Change json format in NSDictionary (Objective C)

212 Views Asked by At

I am new in ios programming. I should apply data to the chart. But the framework(ShinobiControls) which I use accepts only json with certain format. So I have to change my json data format to appropriate. I have NSDictionary which contain json like this:

"data": [
    "01.01.2015",
    "01.01.2015",
    "01.01.2015",
    "01.01.2015"]
"close": [
    [
      1,
      1,
      1,
      1]

And now I should change format of the json like this:

[
  {
    "date": "01.01.2015",
    "close": 1
  },
  {
    "date": "01.01.2015",
    "close": 1
  },
  {
    "date": "01.01.2015",
    "close": 1
  },
  {
    "date": "01.01.2015",
    "close": 1
  }
]

I did some manipulation with converting NSDictionary to NSArray, but didn't get anything. How can I do it? Do you have any ideas? Thank you.

2

There are 2 best solutions below

0
Abd Al-rhman Taher Badary On BEST ANSWER

So if i understand your question right, you have a dictionary that contains 2 arrays and you want to convert it to an array that contains dictionaries , assuming that that the count of the arrays in the dictionary is equal, you can do the following

//This is the first array in your dictionary 
NSArray * dataArr = [data objectForKey:@"data"] ;
//This the second array in your dictionary 
NSArray * closeArr = [data objectForKey:@"close"] ;

NSUInteger  dataCount = [dataArr count] ;
NSUInteger  closeCount = [closeArr count] ;

//This will be your result array
NSMutableArray * newData = [NSMutableArray new] ;

//The loop condition checks that the current index is less than both the arrays 
for(int i = 0 ; i<dataCount && i<closeCount ; i++)
{
    NSMutableDictionary * temp = [NSMutableDictionary new] ;
    NSString * dataString = [dataArr objectAtIndex:i];
    NSString * closeString = [closeArr objectAtIndex:i];
    [temp setObject:dataString forKey:@"date"];
    [temp setObject:closeString forKey:@"close"] ;

    [newData addObject:temp];
}
0
Chirag D jinjuwadiya On
NSArray *Arr = [[NSArray alloc] initWithObjects:@"01.01.2015",@"01.01.2015",@"01.01.2015",@"02.01.2015", nil];
NSArray *Arr1 = [[NSArray alloc] initWithObjects:@"1",@"1",@"1",@"1", nil];
NSDictionary *Dic = [[NSDictionary alloc] initWithObjectsAndKeys:Arr,@"data",Arr1,@"close", nil];
NSLog(@"%@",Dic);
NSMutableArray *ArrM = [[NSMutableArray alloc] init];
for ( int  i = 0; i<Arr.count; i++) {
    NSDictionary *Dic = [[NSDictionary alloc] initWithObjectsAndKeys:Arr[i],@"data",Arr1[i],@"close", nil];
    [ArrM addObject:Dic];
}
NSLog(@"%@",ArrM);
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:ArrM options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);