JSON解析的几种方法?
JSONKit(第三方的解析工具) , NSJSONSerialization (系统提供的解析类,其解析效率最高)
普通方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSON_stu" ofType:@"txt"];
NSData *data = [NSData dataWithContentsOfFile:path];
/*NSJSONReadingMutableContainers = (1UL << 0), //返回一个数组或者字典
NSJSONReadingMutableLeaves = (1UL << 1), //返回一个字符串
NSJSONReadingAllowFragments = (1UL << 2) //返回一个任意类型的对象
*/
//找到最小的数组套字典的
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"array == %@", array);
for (NSDictionary *dic in array) {
NSLog(@"dic === %@", [dic objectForKey:@"content"]);
}
}
调用第三方库的方法
- 文件夹中添加资源文件
- 引入第三方框架 #import "JSONKit.h"
- 修改混编模式
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSON_stu" ofType:@"txt"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSArray *array = [data objectFromJSONData];
NSLog(@"array = %@",array);
}