JSONObjectWithData:options:error:方法來進行數據轉換,這裏的options是一個枚舉值,官方文檔定義是這樣
enum {
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
NSJSONReadingAllowFragments = (1UL << 2)
}; json
這三個的區別含義以下:數組
NSJSONReadingMutableContainers Specifies that arrays and dictionaries are created as mutable objects. // 建立可變的數組或字典 接收
NSJSONReadingMutableLeaves Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString. // 指定在JSON對象可變字符串被建立爲NSMutableString的實例 NSJSONReadingAllowFragments Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary // 指定解析器應該容許不屬於的NSArray或NSDictionary中的實例頂層對象
首先用代碼來講明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-readingurl