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

Parsowanie JSON za pomocą NSJSONSerialization

Przekształcaj odpowiedzi API w użyteczne obiekty Objective-C za pomocą NSJSONSerialization i bezpiecznie poruszaj się po wynikowych słownikach i tablicach.

Parsowanie JSON za pomocą NSJSONSerialization to bezpłatna lekcja Objective-C iOS Development for Legacy & Enterprise Apps na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Objective-C iOS Development for Legacy & Enterprise Apps, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Objective-C iOS Development for Legacy & Enterprise Apps zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Parsowanie JSON za pomocą NSJSONSerialization” jest bezpłatna?

Tak — pełny tekst „Parsowanie JSON za pomocą NSJSONSerialization” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Objective-C iOS Development for Legacy & Enterprise Apps, przejdź na CoddyKit PRO. Kurs Objective-C iOS Development for Legacy & Enterprise Apps zawiera 4 lekcji w sumie.

Co nauczysz się w „Parsowanie JSON za pomocą NSJSONSerialization”?

Przekształcaj odpowiedzi API w użyteczne obiekty Objective-C za pomocą NSJSONSerialization i bezpiecznie poruszaj się po wynikowych słownikach i tablicach. Ćwiczysz Objective-C iOS Development for Legacy & Enterprise Apps z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Objective-C iOS Development for Legacy & Enterprise Apps?

Nie wymagamy żadnego doświadczenia. Objective-C iOS Development for Legacy & Enterprise Apps w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Parsowanie JSON za pomocą NSJSONSerialization”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Objective-C iOS Development for Legacy & Enterprise Apps?

Tak. Każda lekcja Objective-C iOS Development for Legacy & Enterprise Apps zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. NSURLSession do wywołań API
  2. Grand Central Dispatch (GCD)
  3. NSOperationQueue do złożonych zadań
  4. Parsowanie JSON za pomocą NSJSONSerialization
← Powrót do Objective-C iOS Development for Legacy & Enterprise Apps