JSON文档有两种结构:对象、数据
对象:以“{”开始,以"}"结束,是名称/值对儿的集合。名称和值之间用":"隔开。
数组:以"["开始,以"]"结束,中间是数据。数据以,隔开。
JSON.txt文件
[
{
"name":"安越超",
"age":20,
"gender":"male",
"hobby":"play",
"phone":"15801002807"
},
{
"name":"曹贺军",
"age":20,
"gender":"male",
"hobby":"sleep",
"phone":"112332222222"
},
{
"name":"王博南",
"age":20,
"gender":"male",
"hobby":"play",
"phone":"333333333333"
},
{"name":"jdidi",
"age":20,
"gender":"male",
"hobby":"play",
"phone":"333333333333"
}
]
数据模型
.h文件
@interface Student : NSObject
//声明属性
@property(nonatomic,copy) NSString *name;
@property(nonatomic,assign) NSInteger age;
@property(nonatomic,copy) NSString *gender;
@property(nonatomic,copy) NSString *hobby;
@property(nonatomic,copy) NSString *phone;
@end
.m文件
#pragma mark------------防止KVC出错
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
//1.防止键用了关键字
if ([key isEqualToString:@"int"]) {
_age = [value integerValue];
//2.防止key值书写错误
NSLog(@"%@",key);
}
}
#pragma mark----------debug模式校验对象
-(NSString *)description
{
return [NSString stringWithFormat:@"name:%@,age:%ld,gender:%@,hobby:%@,phone:%@",_name,_age,_gender,_hobby,_phone];
}
视图控制器的延展部分:
#pragma mark--------声明一个盛放model对象的数组
@property(nonatomic,strong) NSMutableArray *array;
JSON-Function方法解析JSON数据
- (IBAction)JSONAction:(UIButton *)sender {
//1.获取文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSON" ofType:@"txt"];
//2.根据文件路径创建data对象
NSData *data = [NSData dataWithContentsOfFile:path];
//3.解析
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//NSLog(@"%@",array);
//4.组装
_array = [NSMutableArray arrayWithCapacity:6];
for (NSDictionary *dict in array) {
Student *stu = [Student new];
[stu setValuesForKeysWithDictionary:dict];
[_array addObject:stu];
}
//校验
for (Student *stu in _array) {
NSLog(@"%@",stu);
}
}
JSON-Kit解析方式(要导入JSONKit.h和.m文件)
- (IBAction)jsonWithFSONKitAction:(UIButton *)sender {
//1.获取文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSON" ofType:@"txt"];
//2.根据文件路径创建data
NSData *data = [NSData dataWithContentsOfFile:path];
//3.解析
NSArray *array = [data objectFromJSONData];
//4.组装
_array = [NSMutableArray arrayWithCapacity:6];
for (NSDictionary *dict in array) {
Student *stu = [Student new];
[stu setValuesForKeysWithDictionary:dict];
[_array addObject:stu];
}
//校验
for (Student *stu in _array) {
NSLog(@"%@",stu);
}
}