2012/8/3 (IOS 5 JSON文件处理)

  1. 使用IOS5自带的JSON类,来处理文件 

    1. 先用NSData 来获取网站API内容 通常的表达式为: 

      NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@""] 

      通常在一个GCD block 中异步处理。 

    2. 再通过使用NSJON类的方法来解析该Data 通常表达式为: 

      NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

       

       

  2. 使用IOS5自带的JSON类,来生成JSON文件 

    1. 比如有一个NSArray *testArray 先转换成NSData(JSON) 通常表达式为: 

      NSData* jsonData = [NSJSONSerialization dataWithJSONObject:testArray    options:NSJSONWritingPrettyPrinted error:&error]; 

       

 

 

通常这些方法可以放到JSON转换成的NSArray,NSDictionary,NSString的catagory里去来使代码的可读性提高 

 

如NSDictionary里

@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

下次可以直接来获取一个
    dictionary = [NSDictionary dictionaryWithContentsOfJSONURLString:@"http://www.flickr.com/api=xxxx&call=?"] 

    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndkeys:@"someone", "me", "somegirl", "you", nil];

    NSData *data = [dic toJSON];

 

  原文地址:http://www.raywenderlich.com/5492/working-with-json-in-ios-5 

 

posted @ 2012-08-03 16:55  sayALittle  阅读(457)  评论(0编辑  收藏  举报
点击这里给我发消息