1 JSON基础
JSON全称是JavaScript Object Notation,它是一种轻量级的数据交换格式。JSON数据格式既适合人进行读写,也适合计算机本身解析和生成。早期,JSON是JavaScript语言的数据交换格式,后来发展成为一种与语言无关的数据交换格式。JSON在许多编程语言中使用,包括java、C、Objcetive-C、C++、C#、JavaScript、Perl、Python等。JSON提供了多种语言之间的交换数据的能力,因此,JSON是一种非常理想的数据结构。
服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外)
资料网站:http://www.w3cschool.cc/
JSON主要有两种数据结构。
- 由key-value对组成的数据结构,类似于Objective-C中的字典NSDictionary,如:{"name" :"jack", "age" :10}
- 有序集合,类似于Objective-C中的NSArray,如:
[ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ]
JSON—OC对照表
JSON-OC转换
2 JSON解析方案
JSON的常见解析方案有4种:
苹果原生(自带):NSJSONSerialization(性能最好)
第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差)
提示:JSON本质上是一个特殊格式的字符串,注意不是NSString,JSON的解析是一个非常繁琐的工作!
解析
1 使用NSJSONSerialization解析
http://api.36wu.com/Weather/GetWeather这个网址获取天气信息需要申请key值,试用期小于1天。
-(void)JSONSerializationParse{ NSURL *url = [NSURL URLWithString:@"http://api.36wu.com/Weather/GetWeather"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; //district表示区域id,authkey申请的试用值,只允许试用一天。所以过了2016/9/9就获取不到数据了,key自己去http://www.36wu.com申请试用。 request.HTTPBody = [@"district=101010100&format=json&authkey=b0aa5ef944514793812734e0b36e5740" dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) { NSLog(@"conncetionError:%@",connectionError); NSLog(@"string:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"dictionary:%@",dictionary); NSDictionary *dataDictionary = dictionary[@"data"]; NSLog(@"weather=%@,refreshTime=%@",dataDictionary[@"weather"],dataDictionary[@"refreshTime"]); }]; }
打印如下:
2016-09-09 15:59:01.500 JSON解析[942:983924] conncetionError:(null) 2016-09-09 15:59:01.502 JSON解析[942:983924] string:{"data":{"areaid":101010100,"prov":"北京","city":"北京","district":"北京","dateTime":"2016年9月9日","temp":"31℃","minTemp":"18℃","maxTemp":"31℃","weather":"晴","windDirection":"西风","windForce":"2级","humidity":"27%","img_1":"1","img_2":"4","refreshTime":"15:54"},"message":"OK","status":200} 2016-09-09 15:59:01.503 JSON解析[942:983924] dictionary:{ data = { areaid = 101010100; city = "\U5317\U4eac"; dateTime = "2016\U5e749\U67089\U65e5"; district = "\U5317\U4eac"; humidity = "27%"; "img_1" = 1; "img_2" = 4; maxTemp = "31\U2103"; minTemp = "18\U2103"; prov = "\U5317\U4eac"; refreshTime = "15:54"; temp = "31\U2103"; weather = "\U6674"; windDirection = "\U897f\U98ce"; windForce = "2\U7ea7"; }; message = OK; status = 200; } 2016-09-09 15:59:01.508 JSON解析[942:983924] weather=晴,refreshTime=15:54
2 使用JSONKit解析
需要向工程中导入JSONKit.h和JSONKit.m文件。使用处需要引头文件
#import "JSONKit.h"
由于我导入的这个版本不支持ARC,所以需要对JSONKit.m文件设置禁止ARC
-(void)JSONKitParse{ NSURL *url = [NSURL URLWithString:@"http://api.36wu.com/Train/GetTicketInquiry"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; //查询火车票接口 request.HTTPBody = [@"startStation=北京&arriveStation=上海&date=2016-10-01&authkey=b0aa5ef944514793812734e0b36e5740" dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) { NSLog(@"conncetionError:%@",connectionError); NSLog(@"string:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); //使用JSONkit方法 NSDictionary *dictionary = [data objectFromJSONData]; NSLog(@"dictionary:%@",dictionary); NSArray *dataAry = dictionary[@"data"]; NSLog(@"dataAry count=%lu",(unsigned long)dataAry.count); }]; }
由于数据太多就不全贴出来了。
//只是打印的string中的一部分 {"train_no":"240000G1010C","train_code":"G101","start_station":"北京南","end_station":"上海虹桥","from_station":"北京南","to_station":"上海虹桥","start_time":"06:44","arrive_time":"12:38","day_difference":"0","lishi":"05:54","from_station_no":"01","to_station_no":"11","gg_num":"--","gr_num":"--","qt_num":"--","rw_num":"--","rz_num":"--","tz_num":"--","wz_num":"--","yb_num":"--","yw_num":"--","yz_num":"--","ze_num":"522","zy_num":"47","swz_num":"21"} //这是dictionary中的一部分 { "arrive_time" = "12:38"; "day_difference" = 0; "end_station" = "\U4e0a\U6d77\U8679\U6865"; "from_station" = "\U5317\U4eac\U5357"; "from_station_no" = 01; "gg_num" = "--"; "gr_num" = "--"; lishi = "05:54"; "qt_num" = "--"; "rw_num" = "--"; "rz_num" = "--"; "start_station" = "\U5317\U4eac\U5357"; "start_time" = "06:44"; "swz_num" = 21; "to_station" = "\U4e0a\U6d77\U8679\U6865"; "to_station_no" = 11; "train_code" = G101; "train_no" = 240000G1010C; "tz_num" = "--"; "wz_num" = "--"; "yb_num" = "--"; "yw_num" = "--"; "yz_num" = "--"; "ze_num" = 522; "zy_num" = 47; }
3 使用SBJson解析方法
需要导入SBJson.h文件
#import "SBJson.h"
-(void)SBJsonParse{ NSURL *url = [NSURL URLWithString:@"http://api.36wu.com/Translate/GetTranslate"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; //翻译,不过服务下限了,翻译不出来。不过可以看一下SBJson解析。 request.HTTPBody = [@"q=今天天气很好&output=zh_en&format=json&authkey=b0aa5ef944514793812734e0b36e5740" dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) { NSLog(@"conncetionError:%@",connectionError); NSLog(@"string:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); //使用SBJson方法解析 SBJsonParser *sbJsonParse = [[SBJsonParser alloc] init]; NSDictionary *dictionary = [sbJsonParse objectWithData:data]; NSLog(@"dictionary:%@",dictionary); }]; }
过期了,没能正确翻译。
2016-09-09 17:12:52.218 JSON解析[985:995210] conncetionError:(null) 2016-09-09 17:12:52.220 JSON解析[985:995210] string:{"status":200,"message":"OK","data":[{"dst":"旧服务已下线,请迁移至 http://api.fanyi.baidu.com","src":"The previous service has been closed, please visit http://api.fanyi.baidu.com to apply for new service."}]} 2016-09-09 17:12:52.223 JSON解析[985:995210] dictionary:{ data = ( { dst = "\U65e7\U670d\U52a1\U5df2\U4e0b\U7ebf\Uff0c\U8bf7\U8fc1\U79fb\U81f3 http://api.fanyi.baidu.com"; src = "The previous service has been closed, please visit http://api.fanyi.baidu.com to apply for new service."; } ); message = OK; status = 200; }
4 使用TouchJson解析
解析需要引入头文件
#import "CJSONDeserializer.h"
转换某对象到JSON数据——即生成,序列化操作需要引入文件:
#import "CJSONDataserializer.h"
-(void)TouchJsonParse{ NSURL *url = [NSURL URLWithString:@"http://api.36wu.com/Bus/GetLineInfo"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; //公交查询 一天就过期了这个key值 request.HTTPBody = [@"city=北京&line=21&format=json&authkey=b0aa5ef944514793812734e0b36e5740" dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) { NSLog(@"conncetionError:%@",connectionError); NSLog(@"string:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); //使用TouchJson解析 NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserialize:data error:nil]; NSLog(@"dictionary:%@",dictionary); }]; }
该查询数据很长,就不全贴出来了。
{"name":"21路(北京西站-安华桥北)","info":"北京西站北广场5:00-23:00|安华桥北5:00-23:00 ;10公里以内票价2元,每增加5公里以内加价1元,最高票价4元。持卡乘车普通卡5折、学生卡2.5折优惠。","stats":"北京西站;北京世纪坛医院;皇亭子;军事博物馆;木樨地西;木樨地北;西城桥北5:00-23:00 ;10公里以内票价2元,每增加5公里以内加价1元,最高票价4元。持卡乘车普通卡5折、学生卡2.5折优惠。","stats":"北京西站;北京世纪坛医院;皇亭子;军事博物馆;木樨地西;木樨地北;西城\344\270三里河;三里河东口;二七剧场路北口;儿童医院路口西;月坛体育场;阜成门南;阜成门北;西直门南;索家坟;文慧桥北;明光桥北;蓟门桥;蓟门桥北;塔院小区南门;牡丹园西;牡丹园东;健德门桥西;健德门桥桥北5:00-23:00 ;10公里以内票价2元,每增加5公里以内加价1元,最高票价4元。持卡乘车普通卡5折、学生卡2.5折优惠。","stats":"北京西站;北京世纪坛医院;皇亭子;军事博物馆;木樨地西;木樨地北;西城\344\270三里河;三里河东口;二七剧场路北口;儿童医院路口西;月坛体育场;阜成门南;阜成门北;西直门南;索家坟;文慧桥北;明光桥北;蓟门桥;蓟门桥北;塔院小区南门;牡丹园西;牡丹园东;健德门桥西;健德门桥\344东;地铁北土城站;安贞西里;安华桥北"}
本文由http://blog.csdn.net/vnanyesheshou原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!
作者:VNanyesheshou 发表于2016/9/9 21:10:11 原文链接
阅读:133 评论:0 查看评论