2012-08-27 12 views
13

Sono novizio in iOS dev e sto cercando di analizzare un file JSON locale comecacao-Touch - Come analizzare il file locale JSON

{"quizz":[{"id":"1","Q1":"When Mickey was born","R1":"1920","R2":"1965","R3":"1923","R4","1234","response","1920"},{"id":"1","Q1":"When start the cold war","R1":"1920","R2":"1965","R3":"1923","rep4","1234","reponse","1920"}]}

qui è il mio codice:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]; 
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; 
// Parse the string into JSON 
NSDictionary *json = [myJSON JSONValue]; 

// Get all object 
NSArray *items = [json valueForKeyPath:@"quizz"]; 

NSEnumerator *enumerator = [items objectEnumerator]; 
NSDictionary* item; 
while (item = (NSDictionary*)[enumerator nextObject]) { 
    NSLog(@"clientId = %@", [item objectForKey:@"id"]); 
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]); 
    NSLog(@"job = %@",  [item objectForKey:@"Q2"]); 
} 

Ho trovato su questo sito un esempio ma ottengo il seguente errore

-JSONValore non riuscito. L'errore è: non è previsto il token "separatore di valori" dopo la chiave dell'oggetto.

+0

Il tuo JSON è non valido. –

risposta

14

JSON ha una chiave/notazione strict, le coppie chiave/valore per R4 e la risposta non sono corrette. Prova questo:

NSString *jsonString = @"{\"quizz\":[{\"id\":\"1\",\"Q1\":\"When Mickey was born\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"response\":\"1920\"}]}"; 

Se si legge la stringa da un file, non è necessario tutte le barre
Il file potrebbe essere qualcosa di simile:

{ "quiz": [{"id": "1", "Q1": "Quando Mickey era nato", "R1": "1920", "R2": "1965", "R3": "1923", "R4": "1234", "risposta": "1920"}, {"id": "1", "Q1": "Quando inizia la guerra fredda" "," R1 ":" 1920 "," R2 ":" 1965 "," R3 ":" 1923 "," R4 ":" 1234 "," risposta ":" 1920 "}]}


ho provato con questo codice:

NSString *jsonString = @"{\"quizz\":[{\"id\":\"1\",\"Q1\":\"When Mickey was born\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"response\":\"1920\"}, {\"id\":\"1\",\"Q1\":\"When start the cold war\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"reponse\":\"1920\"}]}"; 
NSLog(@"%@", jsonString); 
NSError *error = nil; 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error]; 

NSArray *items = [json valueForKeyPath:@"quizz"]; 

NSEnumerator *enumerator = [items objectEnumerator]; 
NSDictionary* item; 
while (item = (NSDictionary*)[enumerator nextObject]) { 
    NSLog(@"clientId = %@", [item objectForKey:@"id"]); 
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]); 
    NSLog(@"job = %@",  [item objectForKey:@"Q2"]); 
} 

ho avuto l'impressione, che è stato copiato il vecchio codice, come non si utilizza la serializzazione di mela e un enumeratore invece di Fast Enumeration. La roba intera enumerazione potrebbe essere scritto semplice come

NSArray *items = [json valueForKeyPath:@"quizz"]; 
for (NSDictionary *item in items) { 
    NSLog(@"clientId = %@", [item objectForKey:@"id"]); 
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]); 
    NSLog(@"job = %@",  [item objectForKey:@"Q2"]); 
} 

o anche più elaborato con block based enumeration, hwere avete additionaly un indice, se necessario, per l'enumerazione veloce e sicuro.

NSArray *items = [json valueForKeyPath:@"quizz"]; 
[items enumerateObjectsUsingBlock:^(NSDictionary *item , NSUInteger idx, BOOL *stop) { 
    NSLog(@"clientId = %@", [item objectForKey:@"id"]); 
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]); 
    NSLog(@"job = %@",  [item objectForKey:@"Q2"]); 
}]; 
+0

grazie mille per il vostro aiuto. Un'altra domanda, come posso recuperare un indice oggetto specifico nella matrice e sfogliare il valore della chiave?Voglio dire se voglio selezionare direttamente il secondo oggetto e visualizzare il valore id? – Skunkies

+0

dopo aver analizzato la stringa json, avrai nsarrays e dizionari. così per l'array puoi fare 'item = [items objectAtIndex: 1]' per ottenere il secondo oggetto. Ma questo non ha più niente a che fare con Json. questo è un array standard/roba del dizionario. – vikingosegundo

0

Sembra che ci sia un errore di battitura nel file JSON.

Sostituire
"R4","1234","response","1920" con "R4":"1234","response":"1920"
e
"rep4","1234","reponse","1920" con "rep4":"1234","response":"1920"

2

Usa jsonlint.com per trovare errori nel vostro stringa JSON.
In questo caso, si dice che si deve JSON non valida nei pressi "R4"

4
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"json"]; 
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; 
NSError *error = nil; 
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error]; 
0

Swift 2.3 Io uso un metodo di utilità per convertire i file JSON a un dizionario:

func getDictionaryFromJSON(jsonFileName: String) -> [String: AnyObject]? { 
    guard let filepath = NSBundle.mainBundle().pathForResource(jsonFileName, ofType: "json") else { 
     return nil 
    } 

    guard let data = NSData(contentsOfFile: filepath) else { 
     return nil 
    } 

    do { 
     let dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] 
     return dict 
    } catch { 
     print(error) 
     return nil 
    } 
}