jsonリクエスト結果をフィルタする中空フィールドメソッド

1387 ワード

開発では、戻り結果の値が空の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;

}