NSDictionary json格式字符串转字典,字典转json格式字符串

时间:2021-09-10 18:32:43
 + (NSDictionary *)dictionaryWithJsonString:(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;

 }

 + (NSString*)dictionaryToJson:(NSDictionary *)dic

 {

 NSError *parseError = nil;

 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

 return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

 }