一,JSON反序列化与JSON序列化
JSON的解析(JSON反序列化),返回的是字典或数组
JSON就是字典,是JavaScript的对象表示方法,在网络上都是二进制传输,把二进制数据转成OC对象就是JSON反序列化;
JSON的语法规则:
1,数据在键值对中
2,数据有逗号分隔
3,大括号保存一个对象
4,中括号(即方括号)保存数组(多个对象)
benson.com 可以校验JSON的格式是否正确;
例如:
<html>
<head>
<script>
var json = {"name":"lilei","age":18,"sex":true};
//alert(json.name);
var array = [
{"name":"lilei","age":18,"sex":true},
{"name":"hanmeimei","age":17,"sex":false}
];
// alert(array[1].name);
var json = {"className":"三年一班","students":[
{"name":"lilei","age":18,"sex":true},
{"name":"hanmeimei","age":17,"sex":false}
]};
alert(json.students[1].name);
</script>
</head>
<body>
我的第一个网页
</body>
</html>
JSON的反序列化:
id result = [NSJSONSerialization JSONObjectWithData:data options:0error:NULL];
NSJSONReadingMutableLeaves = (1UL << 1),//返回对象最外层可变;
NSJSONReadingAllowFragments = (1UL << 2)//允许碎片解析,但是必须知道什么类型.
把json数据保存到文件
NSDictionary *dic = @{@"name":@"zhangsan",@"age":@(18)};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:0 error:NULL]; [data writeToFile:@"/Users/Apple/Desktop/111.json" atomically:YES];
读取JSON文件
NSData *data = [NSDatadataWithContentsOfFile:@"/Users/Apple/Desktop/111.json"];
id json = [NSJSONSerializationJSONObjectWithData:data options:0error:NULL];
NSLog(@"%@",json);
/*
The top level object is an NSArray or NSDictionary.
最外的对象类型必须是 NSArray or NSDictionary
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
所有的对象类型
All dictionary keys are instances of NSString.
字典的key类型必须是NSString
Numbers are not NaN or infinity.
数字不能是NaN 或者无线大
*/
注意:1,最外层的对象类型必须是NSArray或者NSDictionary
2,字典的key必须是NSString
3,数字不能是NAN或无限大
4,所有的对象类型必须是NSString,NSNumber,NSArray,NSDictionary,NSNull
//1.手动创建json
// NSString *json = @"{\"name\":\"guangkun\",\"age\":\"67\"}";
// [self postJson:[json dataUsingEncoding:NSUTF8StringEncoding]];
// //2.字典
// NSDictionary *dic = @{@"name":@"guangkun",@"age":@"67"};
// //json序列化
// /*
// 1.要转换的对象
// 2.选项,好看输出
// 3.错误
// */
// NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:0 error:NULL];
//3.数组
// NSDictionary *dic1 = @{@"name":@"guangkun1",@"age":@"671"};
// NSDictionary *dic2 = @{@"name":@"guangkun2",@"age":@"67111"};
// NSArray *array = @[dic1,dic2];
//
// NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
//
//4.自定义对象(对象---转成字典----转成二进制,)
// LBPerson *person = [[CZPerson alloc] init];
// person.name = @"lambo";
// person.age = 18;
// //使用KVC给内部变量赋值
// [person setValue:@(NO) forKey:@"_isYellow"];
//判断对象是否能转换成json
// if (![NSJSONSerialization isValidJSONObject:person]) {
// NSLog(@"不能转");
// return;
// }
//对象转字典
// NSDictionary *personDic = [person dictionaryWithValuesForKeys:@[@"name",@"age",@"_isYellow"]];
// NSLog(@"%@",personDic);
//
// NSData *data = [NSJSONSerialization dataWithJSONObject:personDic options:0 error:NULL];
//5.自定义数组(对象---转成字典--添加到数组--转成二进制)
LBPerson *person = [[LBPersonalloc] init];
person.name = @"盼盼";
person.age = 18;
//使用KVC给内部变量赋值
[person setValue:@(NO)forKey:@"_isYellow"];
LBPerson *person1 = [[LBPersonalloc] init];
person1.name =@"lambo";
person1.age = 18;
//使用KVC给内部变量赋值
[person1 setValue:@(NO)forKey:@"_isYellow"];
NSMutableArray *mArray = [NSMutableArrayarray];
NSArray *array = @[person,person1];
//遍历数组中的person转换成字典
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx,BOOL * _Nonnull stop) {
NSDictionary *personDic = [obj dictionaryWithValuesForKeys:@[@"name",@"age",@"_isYellow"]];
[mArray addObject:personDic];
}];
NSData *data = [NSJSONSerializationdataWithJSONObject:mArray.copyoptions:0error:NULL];
}
二,plist解析,返回的是数组或字典
id result = [NSPropertyListSerializationpropertyListWithData:data options:0format:0error:NULL];
三,XML解析
#import "ViewController.h"
#import "Video.h"
@interface ViewController () <NSXMLParserDelegate>
@property (nonatomic,strong) NSMutableArray *videos;
//当前创建的video对象
@property (nonatomic,strong) Video *currentVideo;
//存储当前节点的内容
@property (nonatomic,copy) NSMutableString *mString;
@end
@implementation ViewController
//懒加载
- (NSMutableArray *)videos {
if (_videos ==nil) {
_videos = [NSMutableArrayarrayWithCapacity:10];
}
return_videos;
}
- (NSMutableString *)mString {
if (_mString ==nil) {
_mString = [NSMutableStringstring];
}
return_mString;
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self loadXML];
}
//异步请求xml
- (void)loadXML {
//异步请求服务器的xml文件
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/videos.xml"];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(@"连接错误 %@",connectionError);
return;
}
//
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode ==200 || httpResponse.statusCode ==304) {
//解析数据
NSXMLParser *parser = [[NSXMLParseralloc] initWithData:data];
//设置代理
parser.delegate = self;
//开始执行代理的方法,代理的方法中开始解析的
[parser parse];
}else{
NSLog(@"服务器内部错误");
}
}];
}
//代理方法执行 和 设置代理属性在同一个线程
//代理的方法
//1 开始解析文档
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"1开始解析文档 %@",[NSThreadcurrentThread]);
}
//2 找开始节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {
//elementName 节点的名称
//attributeDict 标签的属性
NSLog(@"2 找开始节点 %@--%@",elementName,attributeDict);
//如果是video标签,创建video对象
if ([elementName isEqualToString:@"video"]) {
self.currentVideo = [[Videoalloc] init];
self.currentVideo.videoId =@([attributeDict[@"videoId"]intValue]);
//添加到数组中
[self.videosaddObject:self.currentVideo];
}
}
//3 找节点之间的内容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
//
NSLog(@"3找节点之间的内容 %@",string);
//拼接字符串
[self.mStringappendString:string];
}
//4 找结束节点
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
//elementName 节点名称
NSLog(@"4 找结束节点 %@",elementName);
//判断标签是否是对应的属性
if ([elementName isEqualToString:@"name"]) {
self.currentVideo.name =self.mString;
}else if([elementNameisEqualToString:@"length"]) {
self.currentVideo.length =@(self.mString.intValue);
}else if([elementNameisEqualToString:@"videoURL"]) {
self.currentVideo.videoURL =self.mString;
}else if([elementNameisEqualToString:@"imageURL"]) {
self.currentVideo.imageURL =self.mString;
}else if([elementNameisEqualToString:@"desc"]) {
self.currentVideo.desc =self.mString;
}else if([elementNameisEqualToString:@"teacher"]) {
self.currentVideo.teacher =self.mString;
}
//清空可变字符串
[self.mStringsetString:@""];
}
//5 结束解析文档
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"5结束解析文档");
NSLog(@"%@",self.videos);
}
//6 解析出错
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSLog(@"出错");
}
@end