美文网首页iOS Developer
过滤json请求结果中空字段方法

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

作者: 逐步腾飞 | 来源:发表于2016-12-08 17:10 被阅读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;
    
    }
    
    

    相关文章

      网友评论

        本文标题:过滤json请求结果中空字段方法

        本文链接:https://www.haomeiwen.com/subject/kqusmttx.html