0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · Aula

Analisar JSON com NSJSONSerialization

Transforme respostas de APIs em objetos Objective-C utilizáveis com NSJSONSerialization e navegue com segurança pelos dicionários e vetores resultantes.

Analisar JSON com NSJSONSerialization é uma aula grátis de Objective-C iOS Development for Legacy & Enterprise Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Objective-C iOS Development for Legacy & Enterprise Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Objective-C iOS Development for Legacy & Enterprise Apps inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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:

  • NSJSONSerialization maps 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.

Perguntas Frequentes

A aula “Analisar JSON com NSJSONSerialization” é grátis?

Sim — o texto completo de “Analisar JSON com NSJSONSerialization” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Objective-C iOS Development for Legacy & Enterprise Apps, atualize para CoddyKit PRO. O curso de Objective-C iOS Development for Legacy & Enterprise Apps inclui 4 aulas no total.

O que vou aprender em “Analisar JSON com NSJSONSerialization”?

Transforme respostas de APIs em objetos Objective-C utilizáveis com NSJSONSerialization e navegue com segurança pelos dicionários e vetores resultantes. Você pratica Objective-C iOS Development for Legacy & Enterprise Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Objective-C iOS Development for Legacy & Enterprise Apps?

Nenhuma experiência prévia é necessária. Objective-C iOS Development for Legacy & Enterprise Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Analisar JSON com NSJSONSerialization”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Objective-C iOS Development for Legacy & Enterprise Apps?

Sim. Cada aula de Objective-C iOS Development for Legacy & Enterprise Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. NSURLSession para Chamadas de API
  2. Grand Central Dispatch (GCD)
  3. NSOperationQueue para Tarefas Complexas
  4. Analisar JSON com NSJSONSerialization
← Voltar para Objective-C iOS Development for Legacy & Enterprise Apps