1.字典转Json字符串
// 字典转json字符串方法
-(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;
}
2.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;
}
网友评论