iOS中關(guān)于json解析的幾種方式
作為一種輕量級的數(shù)據(jù)交換格式,json正在逐步取代xml,成為網(wǎng)絡(luò)數(shù)據(jù)的通用格式。
有的json代碼格式比較混亂,可以使用此“http://www.bejson.com/”網(wǎng)站來進(jìn)行JSON格式化校驗(點擊打開鏈接)。此網(wǎng)站不僅可以檢測Json代碼中的錯誤,而且可以以視圖形式顯示json中的數(shù)據(jù)內(nèi)容,很是方便。
從IOS5開始,APPLE提供了對json的原生支持(NSJSONSerialization),但是為了兼容以前的ios版本,可以使用第三方庫來解析Json。
本文將介紹TouchJson、 SBJson 、JSONKit 和 iOS5所支持的原生的json方法,解析國家氣象局API,TouchJson和SBJson需要下載他們的庫
TouchJson包下載: http://download.csdn.net/detail/enuola/4523169
SBJson 包下載: http://download.csdn.net/detail/enuola/4523177
JSONKit包下載:http://download.csdn.net/detail/enuola/4523160
下面的完整程序源碼包下載:http://download.csdn.net/detail/enuola/4523223
PS:
國家氣象局提供的天氣預(yù)報接口
接口地址有三個:
http://www.weather.com.cn/data/sk/101010100.html
http://www.weather.com.cn/data/cityinfo/101010100.html
http://m.weather.com.cn/data/101010100.html
第三接口信息較為詳細(xì),提供的是6天的天氣,關(guān)于API所返回的信息請見開源免費(fèi)天氣預(yù)報接口API以及全國所有地區(qū)代碼!?。▏覛庀缶痔峁?/a>,全國各城市對應(yīng)這一個id號,根據(jù)改變id好我們就可以解析出來各個城市對應(yīng)天氣;
下面介紹四種方法解析JSON:
(1)使用TouchJSon解析方法:(需導(dǎo)入包:#import "TouchJson/JSON/CJSONDeserializer.h")
- //使用TouchJson來解析北京的天氣
- - (IBAction)btnPressTouchJson:(id)sender {
- //獲取API接口
- NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];
- //定義一個NSError對象,用于捕獲錯誤信息
- NSError *error;
- NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
- NSLog(@"jsonString--->%@",jsonString);
- //將解析得到的內(nèi)容存放字典中,編碼格式為UTF8,防止取值的時候發(fā)生亂碼
- NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
- //因為返回的Json文件有兩層,去第二層內(nèi)容放到字典中去
- NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
- NSLog(@"weatherInfo--->%@",weatherInfo);
- //取值打印
- txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
- }
(2)使用SBJson解析方法:(需導(dǎo)入包:#import "SBJson/SBJson.h")
- //使用SBJson解析南陽的天氣
- - (IBAction)btnPressSBJson:(id)sender {
- NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101180701.html"];
- NSError *error = nil;
- NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
- SBJsonParser *parser = [[SBJsonParser alloc] init];
- NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];
- NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
- txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
- }
(3)使用IOS5自帶解析類NSJSONSerialization方法解析:(無需導(dǎo)入包,IOS5支持,低版本IOS不支持)
- - (IBAction)btnPressIOS5Json:(id)sender {
- NSError *error;
- //加載一個NSURL對象
- NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
- //將請求的url數(shù)據(jù)放到NSData對象中
- NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
- //IOS5自帶解析類NSJSONSerialization從response中解析出數(shù)據(jù)放到字典中
- NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
- NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
- txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
- NSLog(@"weatherInfo字典里面的內(nèi)容為--》%@", weatherDic );
- }
(4)使用JSONKit的解析方法:(需導(dǎo)入包:#import "JSONKit/JSONKit.h")
- - (IBAction)btnPressJsonKit:(id)sender {
- //如果json是“單層”的,即value都是字符串、數(shù)字,可以使用objectFromJSONString
- NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";
- NSLog(@"json1:%@",json1);
- NSDictionary *data1 = [json1 objectFromJSONString];
- NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
- NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
- [json1 release];
- //如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能會報錯(測試結(jié)果表明:使用由網(wǎng)絡(luò)或得到的php/json_encode生成的json時會報錯,但使用NSString定義的json字符串時,解析成功),最好使用objectFromJSONStringWithParseOptions:
- NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"張三\", \"age\":\"32\"}}";
- NSLog(@"json2:%@", json2);
- NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
- NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
- NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
- [json2 release];
- }
另外,由于iOS5新增了JSON解析的API,我們將其和其他五個開源的JSON解析庫進(jìn)行了解析速度的測試,下面是測試的結(jié)果。
我們選擇的測試對象包含下面的這幾個框架,其中NSJSONSerialization是iOS5系統(tǒng)新增的JSON解析的API,需要iOS5的環(huán)境,如果您在更低的版本進(jìn)行測試,應(yīng)該屏蔽相應(yīng)的代碼調(diào)用。
- - [SBJSON (json-framework)](http://code.google.com/p/json-framework/)
- - [TouchJSON (from touchcode)](http://code.google.com/p/touchcode/)
- - [YAJL (objective-C bindings)](http://github.com/gabriel/yajl-objc)
- - [JSONKit](https://github.com/johnezang/JSONKit)
- - [NextiveJson](https://github.com/nextive/NextiveJson)
- -[NSJSONSerialization](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946)
我們選擇了四個包含json格式的數(shù)據(jù)的文件進(jìn)行測試。每一個文件進(jìn)行100的解析動作,對解析的時間進(jìn)行比較。
.....
測試的結(jié)果顯示,系統(tǒng)的API的解析速度最快,我們在工程項目中選擇使用,也是應(yīng)用較為廣泛的SBJSON的解析速度為倒數(shù)第二差,令我大跌眼鏡。
與系統(tǒng)API較為接近的應(yīng)該是JSONKit。
這里沒有對API的開放接口和使用方式進(jìn)行比較,若單純基于以上解析速度的測試:
1:iOS5應(yīng)該選擇系統(tǒng)的API進(jìn)行
2:不能使用系統(tǒng)API的應(yīng)該選擇JSONKit