码迷,mamicode.com
首页 > Web开发 > 详细

Cocoa 下的 JSON 数据处理

时间:2015-08-31 00:56:33      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

在 Cocoa 下处理 JSON 数据非常方便,核心对象便是 NSJSONSerialization 这个类,它可以完成 JSON 数据与 Foundation 对象之间的相互转换。将 JSON 数据转为 Foundation 对象,使用 JSONObjectWithData。将 Foundation 对象转为 JSON 数据,使用 dataWithJSONObject。这个类也支持流的输入输出。

转换成 JSON 的对象必须具有如下属性:

  1. 顶层对象必须是 NSArray 或者 NSDictionary。
  2. 所有的对象必须是 NSString、NSNumber、NSArray、NSDictionary、NSNull 的实例。
  3. 所有 NSDictionary 的 key 必须是 NSString 类型。
  4. 数字对象不能是非数值或无穷。

所幸 JSON 数据类型基本上都是字符串和整数。对于整数值和布尔值,Cocoa 都是以 NSNumber 封装的,因此 JSON 中的布尔值,需要用 NSNumber 的 boolValue 获取。

比如,简化代码:

NSDictionary *jsonDict = @{@"name":@"catshit", @"id":@1, @"extras":@{@"color":@"black", @"active": @YES, @"option":[NSNull null]}};

NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:nil];

NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

输出 JSON 字符串:

{"name":"catshit","id":1,"extras":{"color":"black","option":null,"active":true}}

将 Foundation 对象转为 JSON 数据时,可以预先用 isValidJSONObject 判断能否转换成功。

 

解析通过 JSONObjectWithData:

NSString *jsonString = @"{\"name\":\"catshit\", \"id\":1, \"extras\":{\"color\":\"black\", \"active\": true, \"option\":null}}";

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

NSLog(@"name = %@", [jsonDict valueForKey:@"name"]);

JSONObjectWithData 其实是返回一个 id 型,因为顶层有可能是 NSArray 或者 NSDictionary,对这个例子来说,顶层是字典。

 

借助于 KVC,访问嵌套数据也十分方便,比如想直接访问 extras 下的 active 是否为真,可以这样:

NSNumber *active = [jsonDict valueForKeyPath:@"extras.active"];

if([active boolValue]) { ... }

 

是不是很简单? NSJSONSerialization 在 Cocoa 和 Cocoa Touch 下都存在,是处理 JSON 很小巧方便的一个类。

 

Cocoa 下的 JSON 数据处理

标签:

原文地址:http://www.cnblogs.com/reviver/p/cocoa-json.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!