字典转 Json , json ->dic

/**

* @brief 把格式化的JSON格式的字符串转换成字典

* @param jsonString JSON格式的字符串

* @return 返回字典

*/

//  json格式字符串转字典:

- (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;

}


// 字典转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

- (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];

//替换掉网址的\转义    \/  替换为 /

[mutStr replaceOccurrencesOfString:@"\\/" withString:@"/" options:NSLiteralSearch range:NSMakeRange(0,mutStr.length)];

return mutStr;

}


字典转 Json , json ->dic_第1张图片
方法一图片



方法二图片

你可能感兴趣的:(字典转 Json , json ->dic)