2011-12-07 152 views
0

它只爲NSMutableDictionary輸出一個集合。我想使用NSMutableDictionary(JSONRepresentation)創建一個JSON請求。NSMutableDictionary沒有得到預期的輸出。

// My code  

NSArray *keysEndpoint = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil]; 
NSArray *objectEndpoint = [NSArray arrayWithObjects:@"622", @"Brand", @"0", nil]; 

NSArray *keysEndpoint1 = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil]; 
NSArray *objectEndpoint1 = [NSArray arrayWithObjects:@"595", @"CK-05052011", @"1", nil]; 

NSMutableArray *keys1 = [[NSMutableArray alloc] initWithCapacity:0]; 
NSMutableArray *objects1 = [[NSMutableArray alloc] initWithCapacity:0]; 

[keys1 addObjectsFromArray:keysEndpoint]; 
[keys1 addObjectsFromArray:keysEndpoint1]; 

NSLog(@"Key Dic: %@", keys1); 

[objects1 addObjectsFromArray:objectEndpoint]; 
[objects1 addObjectsFromArray:objectEndpoint1]; 

NSLog(@"Obje Dic: %@", objects1); 

NSMutableDictionary *testMut = [NSMutableDictionary dictionaryWithObjects:objects1 forKeys:keys1]; 

NSLog(@"Test Dic: %@", testMut); 

輸出是我得到的是這樣的:

Test Dic: { 
    EndpointType = 1; 
    ID = 595; 
    Name = "CK-05052011"; 
} 

Expexted輸出我想要的是:

Test Dic: { 
    EndpointType = 1; 
    ID = 595; 
    Name = "CK-05052011"; 
} 
{ 
    EndpointType = 0; 
    ID = 622; 
    Name = "Brand"; 
} 

回答

1

對於一本字典,將相同的鍵兩次將覆蓋第一組鍵。你應該的NSMutableDictionary的NSMutableArray的

NSArray *keysEndpoint = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil]; 
NSArray *objectEndpoint = [NSArray arrayWithObjects:@"622", @"Brand", @"0", nil]; 

NSArray *keysEndpoint1 = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil]; 
NSArray *objectEndpoint1 = [NSArray arrayWithObjects:@"595", @"CK-05052011", @"1", nil]; 

NSMutableDictionary *testMut = [NSMutableDictionary dictionaryWithObjects:objectsEndpoint forKeys:keysEndpoint]; 


NSMutableDictionary *testMut1 = [NSMutableDictionary dictionaryWithObjects:objectsEndpoint1 forKeys:keysEndpoint1]; 

NSMutableArray * dictArray = [NSMutableArray arrayWithObjects:testMut,testMut1,nil]; 

NSLog(@"Test DictArray: %@", dictArray); 
+0

謝謝你,這個工程篦,但問題是,我有超過20陣列的關鍵點和目標端點。我無法創建20個NSMutableDictionary。有沒有辦法以編程方式做到這一點? – AAV

+0

@AmitVyawahare你從哪裏獲得關鍵點和對象端點數據?動態填充這些數據顯然是可能的。爲了將數據轉換爲json對象,可以在SO上查找SBJson或JSONKit的示例。 –