后臺(tái)返回的數(shù)據(jù)格式由過(guò)去的json與xml并存的時(shí)代涡真,變成了現(xiàn)在的以json為主找筝,xml幾乎不存在的年代脖母,json是每一個(gè)移動(dòng)端程序猿每次與接口打交道都會(huì)遇到的數(shù)據(jù)格式瑟曲,在這個(gè)過(guò)程中好的接口返回格式固然很好饮戳,但是也不能排除一些特例的情況,如接口字段中存在null的情況;
例子
{ "userName": null,
"userImage":null,
"token":null}
如這樣的返回?cái)?shù)據(jù)洞拨,一定讓開發(fā)者頭疼扯罐,這個(gè)時(shí)候,它從嚴(yán)格意義上來(lái)講是一個(gè)正確的數(shù)據(jù)段烦衣,但卻不是我們想要的歹河,我們可以通過(guò)轉(zhuǎn)換的方式來(lái)進(jìn)行解決將其中的null轉(zhuǎn)換成空
如果只是簡(jiǎn)單的json格式,不包含復(fù)雜的數(shù)組花吟,字典秸歧。可以通過(guò)以下方法進(jìn)行轉(zhuǎn)化(已驗(yàn)證有效性)
- (NSDictionary*)transforeNullValueInSimpleDictionaryToBlankString:(id)originJson{
// 判斷originJson是不是一個(gè)有效的字符串
if (![NSJSONSerialization isValidJSONObject:originJson]) {
return nil;
}
NSDictionary *originDic = (NSDictionary*)originJson;
NSMutableDictionary *translatedDic = [NSMutableDictionary dictionary];
[originDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[NSNull class]]) {
[translatedDic setObject:@"" forKey:key];
}else{
[translatedDic setObject:obj forKey:key];
}
return translatedDic;
}
如果包含復(fù)雜的格式衅澈,如字段包含數(shù)組或者字典键菱,就可以采取下面的進(jìn)行修復(fù)(沒(méi)有測(cè)試,可能需要修改,僅提供參考)
- (NSDictionary*)transforeNullValueInDictionaryToBlankString:(id)originJson{
// 判斷originJson是不是一個(gè)有效的字符串
if (![NSJSONSerialization isValidJSONObject:originJson]) {
return nil;
}
NSDictionary *originDic = (NSDictionary*)originJson;
NSMutableDictionary *translatedDic = [NSMutableDictionary dictionary];
[originDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
BOOL isNull = NO;
BOOL isArray = NO;
BOOL isDic = NO;
if ([obj isKindOfClass:[NSNull class]]) {
[translatedDic setObject:@"" forKey:key];
isNull = YES;
}
if ([obj isKindOfClass:[NSArray class]]) {
NSMutableArray *tempArray = [NSMutableArray array];
for (id __strong content in obj) {
if ([content isKindOfClass:[NSNull class]]) {
[tempArray addObject:@""];
}
if ([content isKindOfClass:[NSArray class]]) {
[tempArray addObject: [self transformNullValueInArrayToBlankString:content]];
}
}
[translatedDic setObject:tempArray forKey:key];
isArray = YES;
}
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *tempDic;
tempDic = [self transforeNullValueInDictionaryToBlankString:obj];
isDic = YES;
[translatedDic setObject:tempDic forKey:key];
}
if (isNull || isArray || isDic) {
}else{
[translatedDic setObject:obj forKey:key];
}
}];
return translatedDic;
}
- (NSArray*)transformNullValueInArrayToBlankString:(NSArray*)originArray{
NSMutableArray *tempArray = [NSMutableArray array];
for (id __strong content in originArray) {
if ([content isKindOfClass:[NSNull class]]) {
[tempArray addObject:@""];
}
if ([content isKindOfClass:[NSDictionary class]]) {
[tempArray addObject:[self transforeNullValueInDictionaryToBlankString:content]];
}
if ([content isKindOfClass: [NSArray class]]) {
[tempArray addObject:[self transformNullValueInArrayToBlankString:content]];
}
}
return (NSArray*)tempArray;
}