您的位置:首页 > 理论基础 > 数据结构算法

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

2015-09-26 17:09 597 查看
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 的数据结构及其解析方式请见 /article/11537489.html

GDataXMLNode、JSONKit 资源下载:http://download.csdn.net/my
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: