iOS 处理后台返回Json数据中处理方案
2021-03-04 本文已影响0人
iOS小武哥
iOS小伙伴在开发中进行网络请求数据时,接口可能返回字段为:<null>
然后渲染在Label上面就很不适应,如下图返回来的json数据:

遇到这种情况我就问后台,人家没搭理我...,那我自己进行处理,之前都是判断字符串为:<null>
,就默认设成空串:@""
,这次我们在请求框架AFN中进行限制处理:
在#import "AFURLResponseSerialization.h"
有如下这个方法:
static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
if ([JSONObject isKindOfClass:[NSArray class]]) {
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
for (id value in (NSArray *)JSONObject) {
[mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
id value = (NSDictionary *)JSONObject[key];
if (!value || [value isEqual:[NSNull null]] || [value isEqual:@"<null>"]) {
//这个地方处理,默认设置成@""
[mutableDictionary setObject:@"" forKey:key];
//这个是原来的写法,我们给注释掉了.
// [mutableDictionary removeObjectForKey:key];
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
return JSONObject;
}
然后在我们封装的网络请求框架中代码设置如下:
AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
response.removesKeysWithNullValues = YES;
_sessionManager.responseSerializer = response;