Analizzare JSON con NSJSONSerialization
Trasformi le risposte delle API in oggetti Objective-C utilizzabili con NSJSONSerialization e navighi in sicurezza i dizionari e gli array risultanti.
Analizzare JSON con NSJSONSerialization è una lezione Objective-C iOS Development for Legacy & Enterprise Apps gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Objective-C iOS Development for Legacy & Enterprise Apps, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Objective-C iOS Development for Legacy & Enterprise Apps include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
JSON Meets Objective-C
Most APIs return JSON. Objective-C parses it with the Foundation class NSJSONSerialization, mapping JSON to native objects you already know.
The Type Mapping
JSON maps to Foundation types:
- object ->
NSDictionary - array ->
NSArray - string ->
NSString - number/bool ->
NSNumber - null ->
NSNull
Parsing Data to Objects
Call JSONObjectWithData:options:error: on the raw response data. It returns the top-level dictionary or array.
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data
options:0 error:&error];Always Check the Error
Malformed JSON returns nil and fills the error pointer. Check it before using the result.
if (!json) {
NSLog(@"Parse failed: %@", error.localizedDescription);
return;
}Reading Dictionary Values
Once parsed, access fields by key. Cast to the expected type for clarity.
NSDictionary *user = json;
NSString *name = user[@"name"];
NSNumber *age = user[@"age"];Iterating JSON Arrays
For a list response, loop the array and pull fields from each element.
NSArray *items = json[@"items"];
for (NSDictionary *item in items) {
NSLog(@"%@", item[@"title"]);
}Defensive Type Checks
APIs lie. Verify a value's class before using it to avoid crashes from unexpected shapes.
if ([json isKindOfClass:[NSDictionary class]]) {
// safe to treat as a dictionary
}Handling NSNull
JSON null becomes NSNull, not nil. Sending messages to it crashes, so check for it explicitly.
id value = user[@"nickname"];
if (value == [NSNull null]) { value = nil; }Encoding Back to JSON
To send JSON, go the other way with dataWithJSONObject:.
NSDictionary *body = @{@"name": @"Ada"};
NSData *out = [NSJSONSerialization dataWithJSONObject:body
options:0 error:nil];Mapping to Model Objects
Raw dictionaries are error-prone everywhere. A common pattern wraps parsing in a model's initializer, so the rest of the app uses typed objects instead of stringly-typed keys.
- (instancetype)initWithDictionary:(NSDictionary *)d {
self = [super init];
if (self) { _name = d[@"name"]; }
return self;
}Parse Off the Main Thread
Network responses arrive on a background thread. Parse there, then dispatch UI updates back to the main thread to keep the app responsive.
Quick Check
Test your JSON parsing knowledge.
Recap
You learned JSON parsing in Objective-C:
NSJSONSerializationmaps JSON to Foundation types- Always check the error and the result's class
- JSON null becomes
NSNull, not nil - Encode back with
dataWithJSONObject: - Map dictionaries into typed model objects
Defensive parsing keeps networking code crash-free.
Domande Frequenti
La lezione «Analizzare JSON con NSJSONSerialization» è gratuita?
Sì — il testo completo di «Analizzare JSON con NSJSONSerialization» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Objective-C iOS Development for Legacy & Enterprise Apps, passa a CoddyKit PRO. Il corso Objective-C iOS Development for Legacy & Enterprise Apps include 4 lezioni in totale.
Cosa imparerò in «Analizzare JSON con NSJSONSerialization»?
Trasformi le risposte delle API in oggetti Objective-C utilizzabili con NSJSONSerialization e navighi in sicurezza i dizionari e gli array risultanti. Eserciti Objective-C iOS Development for Legacy & Enterprise Apps con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Objective-C iOS Development for Legacy & Enterprise Apps?
Non è richiesta alcuna esperienza precedente. Objective-C iOS Development for Legacy & Enterprise Apps su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Analizzare JSON con NSJSONSerialization»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Objective-C iOS Development for Legacy & Enterprise Apps?
Sì. Ogni lezione Objective-C iOS Development for Legacy & Enterprise Apps include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- NSURLSession per le chiamate API
- Grand Central Dispatch (GCD)
- NSOperationQueue per attività complesse
- Analizzare JSON con NSJSONSerialization