IOS:OC-JSON数据解析

42 篇文章 0 订阅
32 篇文章 0 订阅

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



作者:任任任任师艳
链接:https://www.jianshu.com/p/467d7a38405b
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值