• iOS JSON 数据解析


    JSON 是比较常用的数据格式,相比 XML 层次更清晰,这里介绍两种解析 JSON 的方式:NSJSONSerialization 和 JSONKit

    NSJSONSerialization 是 iOS 5 以后推出的,比较好用的 JSON 解析包.

    JSON 数据格式由对应的 '[',']' 和 '{','}',前者表示数组,后者表示字典.

    NSJSONSerialization 解析过程:

    1.获取文件路径

    2.获取文件内容

    3.解析

    简单小例子:

     1 - (IBAction)parserJSON:(id)sender {
     2     
     3     //获取文件路径
     4     
     5     NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"];
     6     NSError *error = nil;
     7     NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
     8     NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
     9     if (error == nil) {
    10         NSLog(@"%@",array);
    11     }else {
    12         NSLog(@"%@",error);
    13     }
    14     
    15     //数据封装
    16     
    17     NSMutableArray *arr = [NSMutableArray array];
    18     
    19     for (NSDictionary *dic in array) {
    20         Student *stu = [[Student alloc]initWithDictionary:dic];
    21         [arr addObject:stu];
    22     }
    23     
    24     for (Student *stu in arr) {
    25         NSLog(@"%@",stu);
    26     }
    27 }

    JSONKit 解析:(代码)

     1 - (IBAction)parserJSONWithJESONKIT:(id)sender {
     2     
     3     //获取文件路径
     4     
     5     NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"];
     6     NSError *error = nil;
     7     NSString *JSONStr = [[NSString alloc]initWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:&error];
     8     NSLog(@"%@",JSONStr);
     9     //让jesonKIT 解析 JSON 数据
    10     NSMutableArray *array = [JSONStr objectFromJSONString];
    11     NSLog(@"%ld",array.count);
    12     //数据封装
    13     NSMutableArray *arr = [NSMutableArray array];
    14     
    15     for (NSDictionary *dic in array) {
    16         Student *stu = [[Student alloc]initWithDictionary:dic];
    17         [arr addObject:stu];
    18     }
    19     
    20     for (Student *stu in arr) {
    21         NSLog(@"%@",stu);
    22     }
    23 }

    JSONKit.zip 下载

  • 相关阅读:
    Ubuntu若何开启root用户及此外登录成就的处置
    在Linux操作零碎中若何装配内核
    谭浩强C语身教程第一章C言语概述(1)
    Linux独霸琐细下文件的非凡权限
    关于C#中的String replace 函数
    Animation_01_2011年12月24日13:07:23
    HorizontalScrollView_应用举例
    res/values/colors.xml
    Text_01_2011年12月24日12:57:02
    rubbish
  • 原文地址:https://www.cnblogs.com/Ager/p/4928797.html
Copyright © 2020-2023  润新知