ios开发中经常要用到NSDictionary转成Json格式,或者Json格式转换为NSDictionary字典格式的数据,为了便于这两种类型之间的互相转换,小编封装了NSDictionary字典和JSON字符串NSString互相转换的工具类。
1. NSDictionary字典转Json字符串
+ (NSString*)dictToJSONData:(id)infoDict { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString = @""; if (!jsonData) //如果为空 { NSLog(@"错误: %@", error); } else { jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } //去除掉首尾的空白字符和换行字符 jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; return jsonString; }
2. JSON字符串转化为NSDictionary字典
+ (NSDictionary *)jsonToDictionary:(NSString *)jsonString { if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]; if(err) { NSLog(@"json解析失败:%@",err); return nil; } return dic; }