系统自带的NSJSONSerialization解析json文件

时间:2021-04-08 18:34:34
 #import "ViewController.h"
#import "Student.h"
#import "GDataXMLNode.h"
#import "JSONKit.h" @interface ViewController () <NSXMLParserDelegate> /**
* 存储数据的数组
*/
@property (nonatomic, strong) NSMutableArray *dataArray; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} #pragma mark - 系统自带的json数据解析
- (IBAction)foundationParserActionJSONDocument:(UIButton *)sender { // 1.获取文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"StudentInfo_json.txt" ofType:nil]; // 2.根据路径获取NSData
NSData *data = [NSData dataWithContentsOfFile:path]; // 3.对存储数据的数组进行初始化
self.dataArray = [NSMutableArray array]; // 4.开始进行解析
NSArray *resultArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; // 5.遍历数组,使用KVC给对象赋值
for (NSDictionary *dict in resultArray) { Student *stu = [[Student alloc] init]; // 将数组中的值赋给对象
[stu setValuesForKeysWithDictionary:dict]; // 将对象添加到数组中
[self.dataArray addObject:stu];
} // 遍历检验
for (Student *stu in self.dataArray) {
NSLog(@"name = %@, gender = %@, age = %ld, hobby = %@", stu.name, stu.gender, stu.age, stu.hobby);
} } @end