第一种方法是使用分类给字典添加一个类方法,将字典中的null值全部替换为空字符串,代码如下:
.h文件代码:
@interface NSDictionary (DeleteNull)
+ (id)changeType:(id)myObj;
@end
.m文件代码:
@implementation NSDictionary (DeleteNull)
//将NSDictionary中的Null类型的项目转化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
NSArray *keyArr = [myDic allKeys];
NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
for (int i = 0; i < keyArr.count; i ++)
{
id obj = [myDic objectForKey:keyArr[i]];
obj = [self changeType:obj];
[resDic setObject:obj forKey:keyArr[i]];
}
return resDic;
}
//将NSArray中的Null类型的项目转化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
NSMutableArray *resArr = [[NSMutableArray alloc] init];
for (int i = 0; i < myArr.count; i ++)
{
id obj = myArr[i];
obj = [self changeType:obj];
[resArr addObject:obj];
}
return resArr;
}
//将NSString类型的原路返回
+(NSString *)stringToString:(NSString *)string
{
return string;
}
//将Null类型的项目转化成@""
+(NSString *)nullToString
{
return @"";
}
#pragma mark - 公有方法
//类型识别:将所有的NSNull类型转化成@""
+(id)changeType:(id)myObj
{
if ([myObj isKindOfClass:[NSDictionary class]])
{
return [self nullDic:myObj];
}
else if([myObj isKindOfClass:[NSArray class]])
{
return [self nullArr:myObj];
}
else if([myObj isKindOfClass:[NSString class]])
{
return [self stringToString:myObj];
}
else if([myObj isKindOfClass:[NSNull class]])
{
return [self nullToString];
}
else
{
return myObj;
}
}
使用方法:
[model setValuesForKeysWithDictionary:[NSDictionary changeType:dict]];
第二种方法是利用AFNetworking的自动解析,去除掉值为null的键值对,我挺推崇这种方案的,但还要看个人喜好,装逼一点的就用拓展(个人不推荐)代码如下:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
response.removesKeysWithNullValues = YES;
manager.responseSerializer = response;
manager.requestSerializer = [AFJSONRequestSerializer serializer];