JSON是一种轻量级的数据格式,一般用于数据交互
服务器返回给客户端的数据,一般都是JSON格式或XML格式(文件下载除外)
JSON格式很像OC中的字典和数组
例如:{“name”:”jack”, “age”:10}
{“names”:[“jack”,”rose”,”jim”]}
注意:标准JSON格式中key必须用双引号
想要从JSON中挖掘出具体数据,必须对JSON进行解析,将JSON转换为OC数据类型
在iOS中,JSON的常见解析方案有两种:第三方框架(JSONKit,SBJson,TouchJSON)
苹果自带(NSJSONSerialization)
//JSON和OC的对应关系 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //NSString *strM = @"\{\"error\":\"用户名不存在\"}"; //NSString *strM = @"[\"error\",\"用户名不存在\"]"; //id obj = [NSJSONSerialization JSONObjectWithData:[strM dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil]; NSString *strM = @"\"string\""; //不是数组或字典:NSJSONReadingAllowFragments //strM = “false” 输出:NSNumber 0 //strM = “true” 输出:NSNumber 1 //strM = “null” 输出:NSNull null //注意:[NSNull null]该方法获得的是一个单例,表示为空,可以用在字典或者是数组中 id obj = [NSJSONSerialization JSONObjectWithData:[strM dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@----%@", [obj class], obj); }
//JSON->OC - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //1 确定url NSURL *url = [NSURL URLWithString:@"http://主机地址/路径?参数&参数"]; //2 创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3 发送异步请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //4 解析数据 //data本质上是一个json字符串 //NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); //JSON->OC对象(反序列化) /* 第一个参数:JSON的二进制数据 第二个参数: NSJSONReadingMutableContainers = (1UL << 0), 可变字典和数组 NSJSONReadingMutableLeaves = (1UL << 1), 内部所有的字符串都是可变的(iOS7之后有问题,一般不用) NSJSONReadingAllowFragments = (1UL << 2), 既不是字典也不是数组,则必须使用该枚举值 第三个参数:错误信息 */ NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; NSLog(@"%@", dict[@"error"]); }]; }
//OC->JSON - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSDictionary *dictM = @{ @"name":@"name1", @"age":@30 }; //注意:并不是所有的OC对象都能转换为JSON //1 最外层必须是NSArray或NSDictionary //2 所有的元素必须是 NSString,NSNumber, NSArray,NSDictionary,NSNull //3 字典中所有的key都必须是NSString类型的 //4 所有的NSNumber必须是正确的且不能是无穷大 //判断是否可以转换 BOOL isValid = [NSJSONSerialization isValidJSONObject:dictM]; if(!isValid) { NSLog(@"%zd", isValid); return; } /* 第一个参数:要转换的OC对象 第二个参数:选项NSJSONWritingPrettyPrinted 排版 美观 */ NSData *data = [NSJSONSerialization dataWithJSONObject:dictM options:NSJSONWritingPrettyPrinted error:nil]; NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }
//plist文件转json文件 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSArray *arrayM = [NSArray arrayWithContentsOfFile:@"/Path/FileName.plist"]; //OC->JSON NSData *data = [NSJSONSerialization dataWithJSONObject:arrayM options:NSJSONWritingPrettyPrinted error:nil]; [data writeToFile:@"/Path/FileName.json" atomically:YES]; }