2016-11-19 41 views
0

我是ios編程中的新手。我應該將數據應用於圖表。但是我使用的框架(ShinobiControls)只接受某種格式的json。所以我必須將我的json數據格式更改爲適當的。我的NSDictionary包含JSON這樣的:在NSDictionary中更改json格式(Objective C)

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

現在我應該改變JSON這樣的格式:

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

我做了一些操作與NSDictionary中轉換成的NSArray,但沒有得到任何東西。我該怎麼做?你有什麼想法?謝謝。

回答

0

所以,如果我理解你的問題的權利,你有一個包含2個數組的字典,你想將它轉換爲包含字典的數組,假設字典中的數組的數量是相等的,你可以做以下

//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
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);