首页 > 移动平台 > 详细

iOS 系统自带JSON解析,NSJSONReadingOptions参数解读

时间:2015-03-10 19:06:24      阅读:406      评论:0      收藏:0      [点我收藏+]

开发中,我们经常需要解析JSON数据,系统提供的

[NSJSONSerialization JSONObjectWithData:[objc dataUsingEncoding:NSUTF8StringEncoding]

                                                    options:(NSJSONReadingAllowFragments) error:&error]
解析方法,需要填写一个NSJSONReadingOptions参数

首先用代码来说明NSJSONReadingMutableContainers的作用: 

  1.     NSString *str = @"{\"name\":\"Alice\"}";
  2.     
  3.     NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
  4.     // 程序崩溃,不选用NSJSONReadingOptions,则返回的对象是不可变的,NSDictionary
  5.     [dict setObject:@"male" forKey:@"sex"];
  6.     
  7.     NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
  8.     // 没问题,使用NSJSONReadingMutableContainers,则返回的对象是可变的,NSMutableDictionary
  9.     [dict setObject:@"male" forKey:@"sex"];
  10.     
  11.     NSLog(@"%@", dict);



 
NSJSONReadingMutableContainers:返回可变容器类,NSMutableDictionary或NSMutableArray。 
NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString,目前在iOS 7上测试不好用,应该是个bug,参见: 
http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working 
 
NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“111” 这样的字符串。参见: 
http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading
 

iOS 系统自带JSON解析,NSJSONReadingOptions参数解读

原文:http://www.cnblogs.com/aaalice/p/4326514.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!