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

在开发中我们有时候需要去掉返回结果中那些值为空的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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容