iOS NSJSONSerialization四个枚举

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

复制代码

NSString *str = @"{\"name\":\"kaixuan_166\"}";

NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

// 应用崩溃,不选用NSJSONReadingOptions,则返回的对象是不可变的,NSDictionary

[dict setObject:@"male" forKey:@"sex"];

NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];

// 没问题,使用NSJSONReadingMutableContainers,则返回的对象是可变的,NSMutableDictionary

[dict setObject:@"male" forKey:@"sex"];

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。例如使用这个选项可以解析 @“123” 这样的字符串。参见:

http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading

NSJSONWritingPrettyPrinted:的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。


原文地址:http://www.cocoachina.com/bbs/read.php?tid=110907

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容