アプリなどを開発するブログ

React Native / Swift / Ruby on Railsなどの学習メモ。


iOS5からデフォルトで用意されているJSONパーサー、NSJSONSerializationを使う

Objective-CでJSONをパースするには外部ライブラリを使わないといけなかったのですが、
iOS5から標準でNSJSONSerializationというクラスが用意されました。

使い方は以下。

url = @"http://url.json";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *json_data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *error=nil;

// JSONの型によって、NSDictionaryとNSArrayを使い分ける
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:json_data options:NSJSONReadingAllowFragments error:&error];

NSMutableArray *data = [NSMutableArray array];

for (NSDictionary *obj in jsonObject)
{
    [data addObject:[obj objectForKey:@"key名"]];
}

NSLog(@"data : %@", [data description]);