一般常用方法
+ (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 *)jsonStringWithDict:(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;
}
!!!这个方法有很大弊端:键值对里面的key,value的空格也去掉了。
自定义递归拼接方法:
//dic 转json 自定义的无空格。
+ (NSString *)returnJSONStringWithContainerObj:(NSObject *)obj{
NSString *jsonStr = @"";
if ([obj isKindOfClass:[NSArray class]]) {
jsonStr = @"[";
NSArray *arr = (NSArray *)obj;
for (NSObject *subObj in arr) {
NSString *subStr = [NSString returnJSONStringWithContainerObj:subObj];
jsonStr = [NSString stringWithFormat:@"%@%@,",jsonStr,subStr];
}
jsonStr = [NSString stringWithFormat:@"%@%@",[jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)],@"]"];
}else if ([obj isKindOfClass:[NSDictionary class]]){
NSDictionary *dic = (NSDictionary *)obj;
jsonStr = @"{";
NSArray * keys = [dic allKeys];
for (NSString * key in keys) {
NSObject *subObj = [dic objectForKey:key];
NSString *subStr = [NSString returnJSONStringWithContainerObj:subObj];
jsonStr = [NSString stringWithFormat:@"%@\"%@\":%@,",jsonStr,key,subStr];
}
jsonStr = [NSString stringWithFormat:@"%@%@",[jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)],@"}"];
}else{
jsonStr = [NSString stringWithFormat:@"\"%@\"", obj];
}
return jsonStr;
}
iOS11 后有简单方法
NSJSONWritingOptions
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) { NSJSONWritingPrettyPrinted = (1UL << 0), /* Sorts dictionary keys for output using [NSLocale systemLocale]. Keys are compared using NSNumericSearch. >The specific sorting method used is subject to change. */ NSJSONWritingSortedKeys API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) = (1UL << 1) } API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
对上面字段的解释:
NSJSONWritingPrettyPrinted = (1UL << 0) //是将生成的json数据格式化输出,这样可读性高
NSJSONWritingSortedKeys //输出的json字符串就是一整行作者:Simple_Code
链接:https://www.jianshu.com/p/1e242df1335b