iOS 处理后台返回Json数据中处理方案

iOS小伙伴在开发中进行网络请求数据时,接口可能返回字段为:然后渲染在Label上面就很不适应,如下图返回来的json数据:
1661614840941_.pic.jpg
遇到这种情况我就问后台,人家没搭理我...,那我自己进行处理,之前都是判断字符串为:,就默认设成空串:@"",这次我们在请求框架AFN中进行限制处理:
#import "AFURLResponseSerialization.h"有如下这个方法:
static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
    if ([JSONObject isKindOfClass:[NSArray class]]) {
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
        for (id value in (NSArray *)JSONObject) {
            [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(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[key];
            if (!value || [value isEqual:[NSNull null]] || [value isEqual:@""]) {
                //这个地方处理,默认设置成@""
                [mutableDictionary setObject:@"" forKey:key];
               //这个是原来的写法,我们给注释掉了.
              // [mutableDictionary removeObjectForKey:key];
            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
                mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
            }
        }

        return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
    }

    return JSONObject;
}
然后在我们封装的网络请求框架中代码设置如下:
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    _sessionManager.responseSerializer = response;
这个时候我们在进行网络请求数据的时候看控制台打印,也就没有

你可能感兴趣的:(iOS 处理后台返回Json数据中处理方案)