//字典转json格式字符串:
- (NSString*)dictionaryToJson:(NSDictionary*)dic
{
NSError*parseError =nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
//json格式字符串转字典:
- (NSDictionary*)dictionaryWithJsonString:(NSString*)jsonString {
if(jsonString ==nil) {
returnnil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError*err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
returnnil;
}
returndic;
}
//去空格
-(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];
NSRangerange = {0,jsonString.length};
//去掉字符串中的空格
[mutStrreplaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRangerange2 = {0,mutStr.length};
//去掉字符串中的换行符
[mutStrreplaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
returnmutStr;
}