NSDictionary 字典, JSON 字符串互转

1. NSDictionary->JSON

NSDictionary *jsonDic = @{};

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:0 error:nil]; // 如果不想要 JSON 字符串里带空格或换行等 options 传 0

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

2. JSON->NSDictionary

NSString *jsonString = @"";

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

3. NSJSONReadingOptions 枚举说明

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.

NSJSONReadingAllowFragments // Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.

你可能感兴趣的:(NSDictionary 字典, JSON 字符串互转)