2011-02-07 25 views
8

per favore potete dirmi come passare una stringa JSON che assomiglia a questo:come analizzare JSON in Objective C - SBJSON

{"lessons":[{"id":"38","fach":"D","stunde":"t1s1","user_id":"1965","timestamp":"0000-00-00 00:00:00"},{"id":"39","fach":"M","stunde":"t1s2","user_id":"1965","timestamp":"0000-00-00 00:00:00"}]} 

ho provato in questo modo:

SBJSON *parser =[[SBJSON alloc] init]; 
    NSArray *list = [[parser objectWithString:JsonData error:nil] copy]; 
    [parser release]; 
    for (NSDictionary *stunden in list) 
    { 
     NSString *content = [[stunden objectForKey:@"lessons"] objectForKey:@"stunde"]; 

    } 

grazie a avanzare

migliori saluti

+0

grazie :) non sapevo dove :) – Chris

risposta

22

Nota che i dati JSON ha la seguente struttura:

  1. il valore del livello superiore è un oggetto (un dizionario) che ha un singolo attributo chiamato attributo 'lezioni'
  2. le 'lezioni' è un array
  3. ogni elemento dell'array 'lezioni' è un oggetto (un dizionario contenente una lezione) con diversi attributi, tra 'stunde'

Il codice corrispondente è:

SBJSON *parser = [[[SBJSON alloc] init] autorelease]; 
// 1. get the top level value as a dictionary 
NSDictionary *jsonObject = [parser objectWithString:JsonData error:NULL]; 
// 2. get the lessons object as an array 
NSArray *list = [jsonObject objectForKey:@"lessons"]; 
// 3. iterate the array; each element is a dictionary... 
for (NSDictionary *lesson in list) 
{ 
    // 3 ...that contains a string for the key "stunde" 
    NSString *content = [lesson objectForKey:@"stunde"]; 

} 

Un paio di osservazioni:

  • Nel -objectWithString:error:, il parametro error è un puntatore a un puntatore. È più comune utilizzare NULL anziché nil in questo caso. E 'anche una buona idea non passare NULL e utilizzare un oggetto NSError per ispezionare l'errore nel caso in cui il metodo restituisce nil

  • Se jsonObject viene utilizzato solo in quel particolare metodo, probabilmente non c'è bisogno di copiarlo . Il codice sopra non lo fa.

+0

grazie amico :) – Chris