YOU'VE MADE A BRAVE DECISION, WELCOME.

每一个不曾起舞的日子都是对生命的辜负。

学习JSON解析基础篇

学习JSON解析

  • 系统在带的JSON解析

    • 首先先创建空文件写入json数据

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      [
      {
      "name" : "小明",
      "gender" : "男",
      "age" : "12"
      },
      {
      "name" : "小红",
      "gender" : "女",
      "age" : "18"
      },
      {
      "name" : "小白",
      "gender" : "男",
      "age" : "19"
      }
      ]
    • 先找到文件路径

    1
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"];
    • 再通过文件路径获取数据

      1
      NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
    • 调用系统自带的JSON解析数据的方法,返回一个数组

      1
      2
      NSError *error = nil;
      NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    • 再边里输出数据,其中可以封装一个学生类来遍历。

  • 引入第三方库JOSNKIT来解析

    • 首先导入第三方库, JSONKIT

    • 如果 CMD+R 运行时显示失败,失败的原因是关于ARC,就需要修改工程文件

    • 工程文件—> Build Phases —> Compile Sources —> JSONKIT.m 的 Compiler Flags修改为

      1
      -fno-objc-arc
    • 同理获取文件路径

      1
      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"];
    • 再获得数据内容

      1
      2
      NSString *contentString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
      NSArray *array = [contentString objectFromJSONString];
    • 遍历输出

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      NSMutableArray *studentArray = [[NSMutableArray alloc] initWithCapacity:3];
      for (NSDictionary *dic in array) {
      Student *stu = [[Student alloc] initWithDictionary:dic];
      [studentArray addObject:stu];
      }
      for (Student *stu in studentArray) {
      NSLog(@"%@",stu);
      }