2013-06-09 9 views
14

Ho un NSString che sta memorizzando una matrice JSON sotto forma di NSString. Il NSString chiamato colorArray ha il valore di:Conversione di una NSString di dati JSON su NSArray

[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}]; 

Ho anche un Tableview che vorrei importare l'array in al fine di compilare la tabella. La tabella funziona se carico il tableData in un array come qui di seguito, ma io non riesco a capire come convertire la NSString in un array che può essere utilizzato per compilare la tableData come indicato qui sotto ...

Qualcuno ha idee ? Grazie mille!

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Initialize table data 
    tableData = [NSArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil]; 
} 
+3

-1 Per chiedendo come convertire JSON in NSArray per il tempo 1000i – borrrden

+0

Credo che la sua converte implicitamente se a stringa? – pampi

risposta

37
// Your JSON data: 
NSString *colorArray = @"[{ \"color\":\"Red\" },{ \"color\":\"Blue\" },{ \"color\":\"Yellow\"}]"; 
NSLog(@"colorArray=%@", colorArray); 

// Convert to JSON object: 
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[colorArray dataUsingEncoding:NSUTF8StringEncoding] 
                 options:0 error:NULL]; 
NSLog(@"jsonObject=%@", jsonObject); 

// Extract "color" values: 
NSArray *tableData = [jsonObject valueForKey:@"color"]; 
NSLog(@"tableData=%@", tableData); 

uscita:

 
colorArray=[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}] 
jsonObject=(
     { 
     color = Red; 
    }, 
     { 
     color = Blue; 
    }, 
     { 
     color = Yellow; 
    } 
) 
tableData=(
    Red, 
    Blue, 
    Yellow 
) 

L'ultimo passo utilizza la particolarità di -[NSArray valueForKey:] che restituisce una matrice contenente i risultati di invocare valueForKey: utilizzando il tasto su ciascuno degli oggetti della matrice.

+0

Grazie martin, lo verificherò. La NSString deve contenere le barre in modo che la conversione funzioni correttamente? Grazie ancora! – Brandon

+0

@Brandon: le barre retroverse erano solo necessarie per definire l'input di esempio come costante di stringa nel codice di esempio. –

+0

@Brandon: ho aggiunto alcuni output NSLog per chiarire i passaggi. –

2

Provate

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSString *jsonString = ...//String representation of json 
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
    //colors is a NSArray property used as dataSource of TableView 
    self.colors = [NSJSONSerialization JSONObjectWithData:jsonData 
                options:NSJSONReadingMutableContainers 
                error:nil]; 

} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [self.colors count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    NSDictionary *color = self.colors[indexPath.row]; 
    cell.textLabel.text = color[@"color"]; 

    return cell; 
} 
0

Supponendo che si sta utilizzando ios 5 or higher, serializzazione JSON è costruito in:

NSArray *json = [NSJSONSerialization 
     JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] 
     options:kNilOptions 
     error:&error]; 

Prima di iOS5, è possibile utilizzare SBJSON per ottenere lo stesso:

NSArray *jsonObjects = [jsonParser objectWithString:string error:&error]; 
0

Hai solo bisogno di analizzare il tuo tring in questo modo:

NSString *jsonString = @"[{\"color\":\"Red\" },{\"color\":\"Blue\" },{\"color\":\"Yellow\"}]"; 
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 

NSError *error = nil; 
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error]; 

dopo questo si hanno una serie di dictionay per ottenere tutti i valori che hanno a che fare ciclo matrice e leggere ogni dizionario

NSMutableArray *colorsArray = [NSMutableArray arrayWithCapacity:[jsonArray count]]; 

for (NSDictionary *colorDictionary in jsonArray) { 

    NSString *colorString = [colorDictionary objectForKey:@"color"]; 
    [colorsArray addObject:colorString]; 
} 

Ora colorsArray è NSMutableArray come questo:

[NSMutableArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil]; 
0

Se i vostri dati provengono da un webservice:

NSArray *tableData = [[NSJSONSerialization JSONObjectWithData:request.responseData options: NSJSONReadingMutableContainers error: &error] objectForKey:"yourKeyForColorArray"]; 
1
NSData * data = [colorArray dataUsingEncoding:NSUTF8StringEncoding] 
NSDictionary *JSON = 
    [NSJSONSerialization JSONObjectWithData: data 
            options: NSJSONReadingMutableContainers 
             error: &e]; 

NSArray *tableData = [JSON valueForKey:@"color"]; 

Spero che questo aiuti ..