IOS:OC--JSONKit解析

作者: 任任任任师艳 | 来源:发表于2017-06-03 14:42 被阅读0次

    1.message.txt
    [ {
    "sender":"小花",
    "receiver":"小新",
    "content":"向日葵的微笑永远只为太阳而笑",
    "data":"2017年6月1日"
    },{
    "sender":"小花",
    "receiver":"小新",
    "content":"万丈高楼平地起",
    "data":"2017年6月2日"
    }]

    2.Message.h
    @interface Message : NSObject
    @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.ViewController.m

    import "ViewController.h"

    import "Message.h"

    import "JSONKit.h"

    @interface ViewController ()

    • (IBAction)jsonKit:(UIButton *)sender;
      //存储模型对象:
      @property(nonatomic,strong)NSMutableArray * dataArray;
      @end
    • (IBAction)jsonKit:(UIButton *)sender {
      //获取文件路径
      NSString * filepath = [[NSBundle mainBundle]pathForResource:@"message.txt" ofType:nil ];
      //2.转换放入数据
      NSData * fileData = [NSData dataWithContentsOfFile:filepath];
      NSArray * tempArray = [fileData objectFromJSONData];
      NSLog(@"%@",tempArray);
      //3.初始化数组,再用来接收模型对象
      self.dataArray = [NSMutableArray array];
      //遍历数组,取出字典,然后通过KVC将字典当中元素取出,放入 self.dataArray中
      for (NSDictionary * dict in tempArray) {
      // 创建模型对象
      Message * message = [Message new];
      //通过KVC将字典转化为模型对象
      [message setValuesForKeysWithDictionary:dict];
      [self.dataArray addObject:message];
      }
      //测试
      [self.dataArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
      NSLog(@"%@ %@ %@ %@",[obj sender],[obj receiver],[obj content],[obj data]);
      }];

    }

    相关文章

      网友评论

        本文标题:IOS:OC--JSONKit解析

        本文链接:https://www.haomeiwen.com/subject/tampfxtx.html