JSON
JSON数据传输格式:全称 *JavaScript Object Notation,是基于javascript的轻量级的数据交换格式
JSON值类型
JSON中数据类型 对应 OC中类型
数字(整数或浮点数) NSNumber
字符串(在双引号中) ""
逻辑值(true 或 false)NSNumber
数组(在方括号中) NSArray
对象(字典 在花括号中) NSDictionary
null [NSNull null] 注意在判断值是否为空时使用此种方式
JSON语法
JSON 语法是JavaScript对象表示语法的子集。
数据在 名称/值 对中 (键值对)
数据由逗号分隔 ,
花括号表示对象(OC中的字典){}
方括号表示数组 []
JSON 名称/值对 (键值对)
键/值对组合中的名称(键)写在前面(在双引号中),值写在后面(可以是JSON值支持的数据类型),中间用冒号隔开:
json
{"girlfriends" : [{"name":"林志玲", "age":"18"}, {"name":"林志颖", "age":"28"}, {"name":"林志炫", "age":"38"}, {"name":"阿莲", "age":"16"}], "girlfriendscount": 4}
## JSON解析
***NSJSONSerialization类***
### JSON转字典
JSON转字典
### 字典转JSON
字典转JSON
### 解析注意事项
`NULL` `nil` `Nil` `NSNull`的区别:
NULL C语言中的 表示空指针
nil OC中的 空指针 一般用于对象的空
Nil OC中的 空指针 一般用于类的空
NSNull 空类 该类创建的对象为空对象 表示占位 对象中什么也没有
// JSON解析
// 得到JSON数据
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
// 读取json数据
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
// 查看得到的数据
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonStr==%@", jsonStr);
// NSJSONSerialization 解析
// 1.json数据 2.解析配置 选可变容器 3.错误信息 双指针 在arc下需要加__autoreleasing
NSError *error = nil;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (!error) {
NSLog(@"dic====%@", dic);
// 取错误信息 判断一下
NSLog(@"error_msg==%@", dic[@"error_msg"]);
NSArray *albums = dic[@"albums"];
for (NSDictionary *dic in albums)
{
YKAlbum *album = [YKAlbum new];
[album setValuesForKeysWithDictionary:dic];
[self.albumArray addObject:album];
}
NSLog(@"albumArray===%@", self.albumArray);
// 展示到UI上
}
else
{
NSLog(@"error:%@", error);
}
// 将对象转化为JSON数据,一般用来发送至服务端
// 判断是否可以转化为JSON数据
BOOL isValidJSON = [NSJSONSerialization isValidJSONObject:dic];
NSLog(@"isValidJSON==%d", isValidJSON);
// 将可以转化为json数据的对象转化为json数据
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string==%@", string);