白羽
2018-11-26
来源 :网络
阅读 1341
评论 0
摘要:本文将带你了解IOS开发入门iOS 网络编程 (四)JSON解析,希望本文对大家学IOS有所帮助。
本文将带你了解IOS开发入门iOS 网络编程 (四)JSON解析,希望本文对大家学IOS有所帮助。
1 JSON基础
JSON全称是JavaScript Object Notation,它是一种轻量级的数据交换格式。JSON数据格式既适合人进行读写,也适合计算机本身解析和生成。早期,JSON是JavaScript语言的数据交换格式,后来发展成为一种与语言无关的数据交换格式。JSON在许多编程语言中使用,包括java、C、Objcetive-C、C++、C#、JavaScript、Perl、Python等。JSON提供了多种语言之间的交换数据的能力,因此,JSON是一种非常理想的数据结构。
服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外)
资料网站:https://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解析
https://api.36wu.com/Weather/GetWeather这个网址获取天气信息需要申请key值,试用期小于1天。
-(void)JSONSerializationParse{
NSURL *url = [NSURL URLWithString:@"https://api.36wu.com/Weather/GetWeather"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
//district表示区域id,authkey申请的试用值,只允许试用一天。所以过了2016/9/9就获取不到数据了,key自己去https://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"]);
}];
}
打印如下:
-09-09 15:59:01.500 JSON解析[942:983924] conncetionError:(null)
-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}
-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:@"https://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" = "--";
&nb
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号