过滤json请求结果中空字段方法

2017-01-11 16:04:40来源:http://www.jianshu.com/p/473e45be152c作者:逐步腾飞人点击

第七城市

在开发中我们有时候需要去掉返回结果中那些值为空的property,在AFN中找到一个方法可以帮助我们过滤掉json串中的空值属性。方法如下:


static id QYPPJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
if ([JSONObject isKindOfClass:[NSArray class]]) {
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
for (id value in (NSArray *)JSONObject) {
[mutableArray addObject:QYPPJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
for (id key in [(NSDictionary *)JSONObject allKeys]) {
id value = [(NSDictionary *)JSONObject objectForKey:key];
if (!value || [value isEqual:[NSNull null]]) {
[mutableDictionary removeObjectForKey:key];
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
[mutableDictionary setObject:QYPPJSONObjectByRemovingKeysWithNullValues(value, readingOptions) forKey:key];
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
return JSONObject;
}



第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台