在iOS平台上,Apple 从 iOS 5.0 才开始提供原生的json生成和解析的API,使用起来 很是方便,但这样就没法为iOS 5.0 以前版本的用户服务了。对于iOS 5.0之前的系统,json的使用得益于无数无私的开源拥护者的贡献。估计大多数开发者如今还不会直接抛弃仍在使用 5.0 之前版本的用户,因此这里优先介绍3种主要的开源库的使用,而后再介绍新的原生API的使用。
html
测试数据咱们使用国家气象局提供的天气预报接口: git
咱们打开 github 搜索关键字 json ,程序语言选择 Objective-C ;能够获得 n 页结果。咱们就依次介绍最前面的3个:stig/json-framework、TouchCode/TouchJSON、johnezang/JSONKit。紧接着介绍 iOS 5.0 开始提供的原生 JSON 处理类。 github
此处咱们将这三个开源库及原生JSON处理类放到一个工程里介绍了,但开源库 stig/json-framework 编译是须要ARC支持的,而TouchCode/TouchJSON 和 johnezang/JSONKit 是不须要 ARC 支持。这样我么在工程中就须要打开 ARC (能够在建立工程的时候就选中 ARC,也可和下图同样在build setting 中设置两处 为 YES) 编程
而后对后二者在编译规则中作简单的处理,-fno-objc-arc便是规定该文件编译时不须要ARC支持,以下图:
json
由于咱们测试的数据来自于互联网,因此咱们须要网络支持,这里咱们须要添加系统库:CFNetwork.framework,以下图 浏览器
终于开始写代码了,公用代码: 网络
1.将url地址定义成字符串常量 异步
2.import 相应文件; 测试
3.链接到测试的url; ui
4.取得json数据,并将其以字符串的形式显示在第一个 TextView 上;
5.将解析后的JSON实际内容显示在第二个 TextView 上。
//为了方便,先在工程中的 .pch 文件中定义 字符串常量 #define jsonSourceURLAddress_1 @"http://m.weather.com.cn/data/101010100.html" #define jsonSourceURLAddress_2 @"http://www.weather.com.cn/data/sk/101010100.html" #define jsonSourceURLAddress_3 @"http://www.weather.com.cn/data/cityinfo/101010100.html
#import "LTRootViewController.h" //测试工程中 3 中方式都是在这个controller中使用,将须要的import进来 #import "SBJson.h" #import "TouchJSON/JSON/CJSONDeserializer.h" #import "JSONKit/JSONKit.h"
- (void)viewDidLoad { [super viewDidLoad]; //向开源的地址发送链接请求 //这里使用的是异步的请求 NSURL *url = [NSURL URLWithString:jsonSourceURLAddress_1]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30]; NSURLConnection *urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self]; [urlConnection start]; }
#pragma mark - NSURLConnectionDataDelegate methods - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { UIAlertView * alertV = [[UIAlertView alloc] initWithTitle:@"网络链接失败" message:[NSString stringWithFormat:@"%@",error] delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil]; [alertV show]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //这里咱们终于拿到了网络返回的 JSON 数据 data self.m_JsonData = data; self.m_sourceJsonTV.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; }
- (void)displayWithParsedDic:(NSDictionary *)rootDic { //rootDic 来自与咱们所用的各类方式将 JSON 解析后获得的字典 //下面用于在 TextView 中显示解析成功的JSON实际内容 if (!rootDic) { self.m_parsedJsonTV.text = @"cleaned..."; }else{ NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"]; //因为字典中内容太多,咱们只显示了一部分,诸如 temp2,temp3,...咱们木有在这一一显示 self.m_parsedJsonTV.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气情况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]; } }
如今分类的介绍这4种JSON解析方式:
也有人管这库叫SBJson咱们从 github 上下载 json-framework这个库并将其导入到咱们的工程中(仅需将下载下来的文件夹中,classes 目录下的全部文件复制导入到咱们的工程就行)。在任何你须要使用json处 :#import "SBJson.h"
- (IBAction)sbjsonAction:(id)sender { //此处是使用 json-framework (SBJSON)解析,获得解析后存入字典:rootDic,并显示 SBJsonParser * parser = [[SBJsonParser alloc] init]; NSString * jsonStr = [[NSString alloc] initWithData:self.m_JsonData encoding:NSUTF8StringEncoding]; NSDictionary *rootDic = [parser objectWithString:jsonStr]; [self displayWithParsedDic:rootDic]; }
我纠结了好久,要不要介绍这个库了,由于做者在github上声称:"But you should NOT be using this code in your new projects"。
咱们从 github 上下载 TouchCode/TouchJSON 这个库并将其导入到咱们的工程中(仅需将下载下来的文件夹中,Source 目录下的全部文件复制导入到咱们的工程)。可是 Source/Experimental目录下提供的功能慎用( Be aware that the code in the Experimental subdirectory of Source is just that and may not have been extensively tested and/or have extra dependencies)。在任何你须要使用json处:#import "CJSONDeserializer.h"
- (IBAction)touchJsonAction:(id)sender { //此处是使用 TouchJSON 解析,获得解析后存入字典:rootDic,并显示 NSError * error = nil;//error 用来存储解析过程当中可能出现的错误信息 NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:self.m_JsonData error:&error]; [self displayWithParsedDic:rootDic]; }
咱们从 github 上下载 johnezang/JSONKit 这个库并将其导入到咱们的工程中(这个很简单,代码文件只有2个,都复制导入咱们的工程吧)。
- (IBAction)jsonkitAction:(id)sender { //此处是使用 JSONKit 解析,获得解析后存入字典:rootDic,并显示 NSDictionary * rootDic = [self.m_JsonData objectFromJSONDataWithParseOptions:JKParseOptionLooseUnicode]; [self displayWithParsedDic:rootDic]; }
- (IBAction)nsjsonAction:(id)sender { //此处是使用原生的 JSON 处理类解析,获得解析后存入字典:rootDic,并显示 NSError *error = nil; NSDictionary * rootDic = [NSJSONSerialization JSONObjectWithData:self.m_JsonData options:NSJSONReadingMutableLeaves error:&error]; [self displayWithParsedDic:rootDic]; }
小结:这里只是介绍了最简单的经过网络获得JSON并解析之的方法。在实际应用中咱们可能还要主意在解析时,根据实际传输的数据须要设置的 option 类型。因为本人的水平有限,若是有错我还请各位拍砖,并点出来我必定第一时间更正。
(专门为这篇文章写的demo,貌似oschina木有办法以附件的形式上传。唉!)
经过共享代码上传了 Demo——iOS网络编程: