OS 系统API---NSJSONSerialization四个枚举什么意思
(2014-06-09 14:49:19)
源自:http://www.cocoachina.com/bbs/read.php?tid=110907
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字符串就是一整行。
NSDictionary*dict =@{@"name":@"Jack",@"age":@"18",@"class":@"english"};
//现将字段转成Json格式二进制
NSData*JsonData = [NSJSONSerializationdataWithJSONObject:dictoptions:NSJSONWritingPrettyPrintederror:nil];
//将二进制格式的Json串通过序列化Encoding转化为Json形式的字符串
NSString*dictStr = [[NSStringalloc]initWithData:JsonDataencoding:NSUTF8StringEncoding];
那么,如果是json字符串转字典呢
//先拿到Json字符串,通过序列化转为二进制
NSData*data = [dictStr dataUsingEncoding:NSUTF8StringEncoding];
//这一步就很简单了,直接用苹果那一套,但有一点要注意的是,在这两种互转的过程中,options的选项是不同的,一个是NSJSONWritingPrettyPrintederror,另一个是NSJSONReadingMutableContainerserror。
NSDictionary*dicts = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];