iOS —— JSON 数据结构及其解析方式

JSON数据结构基本概念

1.JSON:(和XML一样都是用来传数据的)轻量级的数据交换格式,正在逐步取代XML.

2.JSON的应用场景:(数据量小,轻量级)移动开发中绝大多数还是使用JSON

3.Javascript Object Notation ,由于JSON解析便捷、快速,并且相同数据用JSON编辑所占的内存更小,所以在iOS中我们我们使用JSON解析更加普遍。

4.JSON文档有两种结构:对象 、数据
对象:以“{“开始,以”}”结束,是“名称/值”对儿的集合。名称和值中间用“:”隔开。多个“名称/值”对之间用“,”隔开。类似OC中的字典。
数组:以“[“开始,以“]”结束,中间是数据。数据以“,”分割。
JSON中的数据类型:字符串、数值、BOOL、对象、数组。
例如:

这里写图片描述
这里写图片描述

JSON 解析:系统方式

解析出来的数据需要进行反序列化,方法如下:
[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

//存放model 对象的容器
@property (nonatomic, strong) NSMutableArray * array;

#pragma mark -JSONFoundation 解析 (系统)
- (IBAction)jsonFoundationAction:(id)sender {
//    1.获取文件路径
    NSString * path = [[NSBundle mainBundle] pathForResource:@"Person" ofType: @"txt"];
//  2.创建data 对象
    NSData * data = [NSData  dataWithContentsOfFile:path];

//   3.解析 (解析的数据在 数组中,数组中存储的是字典) NSJSONReadingAllowFragments 允许有碎片(是一个枚举)
    NSArray * array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

//    4. 组装 (将解析的数据存储到  _array 数组中,组装后的是数组)
    _array = [[NSMutableArray alloc] initWithCapacity:6];
    for (NSDictionary * dict  in array) {
        Student * stu = [Student new];
        [stu setValuesForKeysWithDictionary:dict];
        [_array addObject:stu];
    }
  //   校验
    for (Student * stu in _array) {
        NSLog(@"%@",stu);
    }
}

JSONKit的使用

// 1. 下载文件:https://github.com/johnezang/JSONKit
// 2. 引入到工程中
// 3. 添加libz.1.2.5.dylib到工程中
// 4. 在需要使用的类中引入头文件: #import “JSONKit.h”
// 5. 下面看代码

#pragma mark- JSONKit 解析 (第三方)
- (IBAction)jsonKitAction:(id)sender {
//    1.获取文件路径
    NSString * path = [[NSBundle mainBundle]pathForResource:@"Person" ofType:@"txt"];
//   2. 创建data 对象
    NSData *data = [NSData dataWithContentsOfFile:path];
//    3.解析 (简便的地方,其他都一样)
    NSArray * array = [data objectFromJSONData];
//    4. 组装
    _array = [[NSMutableArray alloc] initWithCapacity:6];
    for (NSDictionary * dict  in array) {
        Student * stu = [Student new];
        [stu setValuesForKeysWithDictionary:dict];
        [_array addObject:stu];
    }
    //   校验
    for (Student * stu in _array) {
        NSLog(@"%@",stu);
    }
}

数据解析:从某种格式的数据提取自己所需要的数据
主流的数据交换格式有:XML 、JSON
XML 解析分为两种:SAX 解析、DOM解析
XML 解析工具:NSXMLParser、GDataXMLNode、TochXML、KissXML等。
JSON解析工具JSONKit、NSJSONSerialization、TouchJSON、SBJSON ,其中NSJSONSerialization 是系统提供的解析类,其解析效率是最高的。

xml 的数据结构及其解析方式请见 http://blog.csdn.net/ci915194561/article/details/48752123
GDataXMLNode、JSONKit 资源下载:http://download.csdn.net/my

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值