2012-08-17 159 views
1

此代碼:轉換字典成一個陣列

for (NSDictionary *object in JSONArray) { 
     NSMutableArray *birdtemp = [[NSMutableArray alloc] initWithObjects:object[@"case_name"], nil]; 
     [allparts addObject:birdtemp]; 
    } 

輸出此日誌:

log: (
     (
     "NZXT Phantom 410" 
    ), 
     (
     "Thermaltake MK+" 
    ) 
) 

我想知道我可以使用什麼樣的代碼,以使該登錄到一個數組,如:

log: (

    "NZXT Phantom 410", 
    "Thermaltake MK+" 
) 

Json陣列是:

log: (
     { 
     "case_color" = White; 
     "case_description" = ""; 
     "case_image" = "http://sitecom/get/parts/part_images/nzxtphantom410.jpeg"; 
     "case_name" = "NZXT Phantom 410"; 
     "case_price" = "99.99"; 
     "case_type" = ATX; 
     id = 1; 
    }, 
     { 
     "case_color" = Black; 
     "case_description" = ""; 
     "case_image" = "http://site.com/get/parts/part_images/thernaltake-mkplus.jpeg"; 
     "case_name" = "Thermaltake MK+"; 
     "case_price" = "84.99"; 
     "case_type" = ATX; 
     id = 2; 
    } 
) 
+0

什麼是JSONArray可以如何打印它的未來 – sachin 2012-08-17 07:23:46

+0

[array addObject:dictionaryObject]; – Tendulkar 2012-08-17 07:24:04

回答

1

Troubleshooted並得到了這一點:

allparts = [[NSMutableArray alloc] init]; 
    NSString *birdtemp; 
    for (NSDictionary *object in JSONArray) { 
      birdtemp = object[@"case_name"]; 
     [allparts addObject:birdtemp]; 
    } 
0
NSMutableArray *birdtemp = [NSMutableArray ....]; 
    for (NSDictionary *object in JSONArray) { 
       [birdtemp addObject:object[@"case_name"]]; 
     } 
    [allparts addObject:birdtemp]; 
1

一個簡單的方法來獲得你正在尋找的結果是使用鍵 - 值編碼(KVC):

NSArray *allparts = [JSONArray valueForKey:@"case_name"]; 

鍵值這種方式在陣列上使用的編碼起初看起來有點反直覺,但它非常強大。

1
NSMutableArray *array = [[NSMutableArray alloc] init]; 
    for (NSDictionary *dict in JSONArray) { 

     [array addObject:[dict objectForKey:@"case_name"]]; 
    } 
    NSLog(@"Your Array: %@",array); 

我認爲這會對您有所幫助。