iOS Developer

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

2016-12-08  本文已影响723人  逐步腾飞

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

}

上一篇下一篇

猜你喜欢

热点阅读