1.与字典转换
NSDictionary *dic = @{@"name":@"macRong",@"webHome":@"eqi.cc"};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"NSDictionary 转 NSData = %@",data);
NSLog(@"NSData 转 NSDictionary =%@",dictionary);
2.与字符串转换
NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding];
NSString *result = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
NSLog(@"NSString 转 NSData = %@",xmlData);
NSLog(@"NSData 转 NSString =%@",result);
3.//字典转json格式字符串
- (NSString *)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
- (NSString *)convertToJsonData:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
NSRange range = {0,jsonString.length};
//去掉字符串中的空格
[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
//去掉字符串中的换行符
[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
return mutStr;
}