Working with JSON in iOS 5 Tutorial

Tutorial by Marin Todorov:

iOS 5 has some new built-in APIs to make it really easy to read and write JSON.

He's right.

I've done half of the tutorial using the public Twitter timeline (JSON) instead. It's available for download here.

Perhaps the coolest part I've left out are the categories that extend the classes to make life even simpler.

@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:
  (NSString*)urlAddress;
-(NSData*)toJSON;
@end
 
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:
  (NSString*)urlAddress
{
    NSData* data = [NSData dataWithContentsOfURL:
      [NSURL URLWithString: urlAddress] ];
    __autoreleasing NSError* error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data
      options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}
 
-(NSData*)toJSON
{
    NSError* error = nil;
    id result = [NSJSONSerialization dataWithJSONObject:self
      options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}
@end
 
Posted Tuesday, January 17th, 2012 under iOS, link, programming.

Tags: ,

Comments are closed.