OS 系統(tǒng)API---NSJSONSerialization四個(gè)枚舉什么意思
(2014-06-09 14:49:19)
源自:http://www.cocoachina.com/bbs/read.php?tid=110907
NSJSONReadingMutableContainers:返回可變?nèi)萜?,NSMutableDictionary或NSMutableArray。
NSJSONReadingMutableLeaves:返回的JSON對(duì)象中字符串的值為NSMutableString,目前在iOS 7上測(cè)試不好用,應(yīng)該是個(gè)bug,參見:
http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working
NSJSONReadingAllowFragments:允許JSON字符串最外層既不是NSArray也不是NSDictionary,但必須是有效的JSON Fragment。例如使用這個(gè)選項(xiàng)可以解析 @“123” 這樣的字符串。參見:
http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading
NSJSONWritingPrettyPrinted:的意思是將生成的json數(shù)據(jù)格式化輸出,這樣可讀性高,不設(shè)置則輸出的json字符串就是一整行。
NSDictionary*dict =@{@"name":@"Jack",@"age":@"18",@"class":@"english"};
//現(xiàn)將字段轉(zhuǎn)成Json格式二進(jìn)制
NSData*JsonData = [NSJSONSerializationdataWithJSONObject:dictoptions:NSJSONWritingPrettyPrintederror:nil];
//將二進(jìn)制格式的Json串通過序列化Encoding轉(zhuǎn)化為Json形式的字符串
NSString*dictStr = [[NSStringalloc]initWithData:JsonDataencoding:NSUTF8StringEncoding];
那么,如果是json字符串轉(zhuǎn)字典呢
//先拿到Json字符串,通過序列化轉(zhuǎn)為二進(jìn)制
NSData*data = [dictStr dataUsingEncoding:NSUTF8StringEncoding];
//這一步就很簡(jiǎn)單了,直接用蘋果那一套,但有一點(diǎn)要注意的是,在這兩種互轉(zhuǎn)的過程中,options的選項(xiàng)是不同的,一個(gè)是NSJSONWritingPrettyPrintederror,另一個(gè)是NSJSONReadingMutableContainerserror。
NSDictionary*dicts = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];