Search code examples
objective-cjsonchartsnsdictionaryshinobi

Change json format in NSDictionary (Objective C)


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.


Solution

  • 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];
    }