IOS:OC-JSON数据解析

1.先建立一个message.txt文档,内容如下:

[ {

"sender":"小花",

"receiver":"小新",

"content":"向日葵的微笑永远只为太阳而笑",

"data":"2017年6月1日",

},{

"sender":"小花",

"receiver":"小新",

"content":"万丈高楼平地起",

"data":"2017年6月2日",

}]

2.Message.h中声明属性,

@property(nonatomic,copy)NSString * sender;

@property(nonatomic,copy)NSString * receiver;

@property(nonatomic,copy)NSString * content;

@property(nonatomic,copy)NSString * data;

3.Message.m中写一个防崩的方法

//防崩

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

4.在storyboard中拖一个button控件,并关联方法

5.ViewController.m

<1>定义一个属性

@property(nonatomic,strong)NSMutableArray * dataArray;

<2>在方法中开始解析

```c

//Json解析,使用系统自带JSON解析

- (IBAction)JsonSystem:(UIButton *)sender {

//1.获取文件路径

NSString * filepath = [[NSBundle mainBundle]pathForResource:@"message.txt" ofType:nil];

//2.转化为数据  创建data对象接收数据

NSData * fileData = [NSData dataWithContentsOfFile:filepath];

//3.使用系统提供JSON类;;;将需要解析的文件传入,由于外层是数组,所以最后解析的数据,应该由数组接收

NSArray * tempArray = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingAllowFragments error:nil];

NSLog(@"%@",tempArray);

//更新数据  初始化数组:

self.dataArray = [NSMutableArray array];

//3.1 遍历JSON获取到的数据

for (NSDictionary * dic in tempArray) {

NSLog(@"%@",dic[@"content"]);

//3.2创建模型对象

Message * message = [Message new];

[message setValuesForKeysWithDictionary:dic];

//3.3将模型数据放入数组内部

[self.dataArray addObject:message];

}

//测试打印

[self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

NSLog(@"%@  %@  %@  %@",[obj receiver],[obj content],[obj data],[obj sender]);

}];

```c

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容