NSJSONSerializationによるJSONのパース
NSJSONSerializationを使ってAPIレスポンスを利用可能なObjective-Cオブジェクトに変換し、生成された辞書や配列を安全に扱います。
「NSJSONSerializationによるJSONのパース」はCoddyKit上の無料Objective-C iOS Development for Legacy & Enterprise Appsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはObjective-C iOS Development for Legacy & Enterprise Apps学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Objective-C iOS Development for Legacy & Enterprise Appsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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.
AI チューターと学ぶ Objective-C — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 12
- レッスン
- 48
よくある質問
「NSJSONSerializationによるJSONのパース」レッスンは無料ですか?
はい。「NSJSONSerializationによるJSONのパース」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Objective-C iOS Development for Legacy & Enterprise Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Objective-C iOS Development for Legacy & Enterprise Appsコースには全4レッスンが含まれています。
「NSJSONSerializationによるJSONのパース」で何を学びますか?
NSJSONSerializationを使ってAPIレスポンスを利用可能なObjective-Cオブジェクトに変換し、生成された辞書や配列を安全に扱います。 ブラウザで直接実行するハンズオンコードでObjective-C iOS Development for Legacy & Enterprise Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Objective-C iOS Development for Legacy & Enterprise Appsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのObjective-C iOS Development for Legacy & Enterprise Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「NSJSONSerializationによるJSONのパース」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このObjective-C iOS Development for Legacy & Enterprise Appsレッスンでコードを書いて実行できますか?
はい。すべてのObjective-C iOS Development for Legacy & Enterprise Appsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- API呼び出しのためのNSURLSession
- Grand Central Dispatch(GCD)
- 複雑なタスクのためのNSOperationQueue
- NSJSONSerializationによるJSONのパース