json

来源:互联网 发布:java编写的游戏引擎 编辑:程序博客网 时间:2024/06/03 06:28

什么是json?
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。采用完全独立于语言的文本格式,易于人阅读和编写,同时也易于机器解析和生成(网络传输速率)。

JSON 数据的书写格式是:名称/值对

JSON 值可以是:
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在方括号中)
对象(在花括号中)
null
对象表示为“{}”括起来的内容 -> OC字典
数组表示“[]”括起来的内容

这句代码负责把JSONObject转成data

[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]

这里object也可以直接用json格式的字符串,比如:
NSString *str = @”{\”name\” : \”liuzhen\”, \”age\” : 123}”;

// NSJSONSerialization是json格式化器,转换器,解析器// JSON -> NSDictionary/NSArray

1.0 字符串类型json数据转化nsdata类型

 NSString *jsonStr = @"{\"name\":\"liu\", \"age\":18}"; NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];

2.0 OC对象dictionary -> Data
// 参数:
// 1. 对象 数组/字典 (也可以是符合json格式的字符串)
// 2. 选项
// 3. NSError对象地址

NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

读取文件

NSData *jsonData = [NSData dataWithContentsOfFile:PATH]; // 也可以用NSFileHandle读取文件内容            // Data -> Dictionary            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
0 0