iOS开发之解析JSON文件

2015-10-22  本文已影响1509人  与佳期

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。所谓的轻量级是与XML文档结构相比,描述项目字符少,所以描述相同的数据所需的字符个数更少,传输速度更高,流量更少

首先对比一下各方法解析JSON文件的效率


json解析速度对比(图片来自网络)

不难看出NSJSONSerialization在效率上完胜JSONKit、SBJSON、TouchJSON、YAJL、NextiveJson。
本文主要介绍NSJSONSerialization和JSONKit两种方法解析JSON文件

NSJSONSerialization解析JSON文件

NSJSONSerialization是iOS5中新增的解析JSON的api,提供了将:

将JSON数据转换为Foundation对象

不废话、上代码
- (void)test1 {
NSString *urlStr = @"http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
NSLog(@"解析失败--%@", error);
return;
}
NSLog(@"-json: %@",json);

    NSArray *array = [json objectForKey:@"song"];
    NSLog(@"--song array: %@",array);

    NSDictionary *jsonDict = [array objectAtIndex:0];
    NSLog(@"-----song jsonDict: %@",jsonDict);
}

结果如图(部分)


屏幕快照 2015-10-22 20.40.53.png
Foundation对象转换为JSON数据
- (void)test2 {
    NSDictionary *song = [NSDictionary dictionaryWithObjectsAndKeys:@"gonghonglou",@"name",@"18",@"age",@"man",@"sex", nil];
    if ([NSJSONSerialization isValidJSONObject:song])
    {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:song options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
}

结果如图


屏幕快照 2015-10-22 20.50.06.png

JSONKit的解析JSON数据

将JSONKit.h、JSONKit.m文件导入工程中,使用时引入头文件:#import "JSONKit.h"
- (void)test3 {
NSString *urlStr = @"http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];

    JSONDecoder *jd = [[JSONDecoder alloc] init];
    NSDictionary *jsonDict = [jd objectWithData: data];
    NSLog(@"json jsonDict:%@",jsonDict);

}

结果如图


屏幕快照 2015-10-22 20.55.31.png

另:关于JSONKit不支持ARC的解决方法

由于项目已经很久没有更新,仍然使用MRC,因此在使用时需要做如下几处修改:

搞定!

后记

小白出手,请多指教。
如言有误,还望斧正!

上一篇下一篇

猜你喜欢

热点阅读