什么是 JSON 数据
JSON 是一种轻量级的数据格式,一般用于数据交互; 服务器返回给客户端的数据,一般都是 JSON 格式或者 XML 格式(文件下载除外); JSON 的格式很像 OC 中的字典和数组,如: {"name" : "jack", "age" : 10} {"names" : ["jack", "rose", "jim"]} 标准 JSON 格式的注意点:key 必须用双引号
JSON - OC 转换对照表
JSON | OC |
---|---|
大括号 { } | NSDictionary |
中括号 [ ] | NSArray |
双引号 " " | NSString |
数字 8、10.9 | NSNumber |
OC 中,JSON 格式的数据解析方案
第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差) 苹果原生(自带):NSJSONSerialization(性能最好)
- //NSJSONSerialization的常见方法
- //JSON数据 -> OC对象
- + (id) JSONObjectWithData: (NSData * ) data options: (NSJSONReadingOptions) opt error: (NSError * *) error;
- //OC对象 -> JSON数据
- + (NSData * ) dataWithJSONObject: (id) obj options: (NSJSONWritingOptions) opt error: (NSError * *) error;
苹果原生方法介绍
OC 对象 转 JSON(序列化) 。并非所有的 OC 对象都能转成 JSON 数据,苹果提供的 API 截图:
isValidJSONObject.png
- NSDictionary * dictM = @ {@"name": @"dasheng11",
- @"age": @3
- };
- NSArray * arrayM = @ [@"123", @"456"];
- //注意:并不是所有的OC对象都能转换为JSON
- /*
- - 最外层必须是 NSArray or NSDictionary
- - 所有的元素必须是 NSString, NSNumber, NSArray, NSDictionary, or NSNull
- - 字典中所有的key都必须是 NSStrings类型的
- - NSNumbers不能是无穷大
- */
- NSString * strM = @"WENIDNGDING";
- BOOL isValid = [NSJSONSerialization isValidJSONObject: strM];
- if (!isValid) {
- NSLog(@"%zd", isValid);
- return;
- }
- //OC--->json
- /*
- 第一个参数:要转换的OC对象
- 第二个参数:选项NSJSONWritingPrettyPrinted 排版比较美观,就是添加了换行
- */
- NSData * data = [NSJSONSerialization dataWithJSONObject: strM options: NSJSONWritingPrettyPrinted error: nil];
- NSLog(@"%@", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]);
JSON 数据转 OC 对象(反序列化)。
- //JSON--->oc对象 反序列化
- /*
- 第一个参数:JSON的二进制数据
- 第二个参数:返回数据格式的选择。默认传0或kNilOptions
- 第三个参数:错误信息
- */
- /*
- NSJSONReadingMutableContainers = (1UL << 0), 可变字典和数组
- NSJSONReadingMutableLeaves = (1UL << 1), 内部所有的字符串都是可变的 ios7之后又问题 一般不用
- NSJSONReadingAllowFragments = (1UL << 2) 既不是字典也不是数组,则必须使用该枚举值
- */
- NSString * strM = @"\"ceshizifuchuan\"";
- // 对于解析出来的数据格式为字典或数组时,options传kNilOptions即可,该宏就是0
- // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
- // 在我们知道解析出来的数据格式时,我们可直接使用该数据格式接受
- id obj = [NSJSONSerialization JSONObjectWithData: [strM dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingAllowFragments error: nil];
- NSLog(@"%@---%@", [obj class], obj);
JSON 数据格式化中的细节
- //NSString *strM = @"{\"error\":\"用户名不存在\"}";
- //NSString *strM = @"[\"error\",\"用户名不存在\"]";
- //NSString *strM = @"\"wendingding\"";
- //NSString *strM = @"false";
- //NSString *strM = @"true";
- NSString * strM = @"null";
- id obj = [NSJSONSerialization JSONObjectWithData: [strM dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingAllowFragments error: 0];
- NSLog(@"%@---%@", [obj class], obj);
- /*
- JOSN OC
- {} @{}
- [] @[]
- "" @""
- false NSNumber 0
- true NSNumber 1
- null NSNull为空
- */
- //nil 字典或数组存放的对象不能为nil
- [NSNull null]; //该方法获得的是一个单粒,表示为空,可以用在字典或者是数组中
来源: http://www.jianshu.com/p/928445e5077f