@chenbinghua
2018-08-16T16:02:14.000000Z
字数 2583
阅读 1790
iOS笔记
参考文章
nil / Nil / NULL / NSNull
ios nil、NULL和NSNull 的使用
模拟服务器返回数据
iOS解决json串中的NSNull类型
NSNull Category
一图胜千言
NSNull在Foundation和其它框架中被广泛的使用,以解决如NSArray和NSDictionary之类的集合不能有nil值的缺陷。你可以将NSNull理解为有效的将NULL或者nil值封装boxing,以达到在集合中使用它们的目的
场景:服务器返回的原始Json数据
{
"status": 1,
"service_name": null,
"service_id": null,
"img_url": "http://api.jgfw.me/assets/uploads/files/",
"price": null,
"num": 3,
"service_info": {
"service_type": null,
"service_time": null,
"service_detail": null,
"customer_name": null,
"customer_phone": null,
"customer_address": "",
"new_jishi": "",
"old_jishi": null,
"lat": null,
"lon": null
},
"order_info": {
"order_no": "E15031267469289848688",
"pay_time": null,
"order_time": null,
"price": 0,
"order_state": null
}
}
AFN请求后打印出来的数据
点击http://www.mocky.io/v2/58997cf60f000094021f4ae7
就可以访问访问的json数据
然后用AFN访问。
//
// Util.m
// AFNDemo
//
// Created by 陈炳桦 on 17/2/7.
// Copyright © 2017年 la.baibu. All rights reserved.
//
#import "Util.h"
@implementation Util
#pragma mark - 私有方法
//将NSDictionary中的Null类型的项目转化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
NSArray *keyArr = [myDic allKeys];
NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
for (int i = 0; i < keyArr.count; i ++)
{
id obj = [myDic objectForKey:keyArr[i]];
obj = [self changeType:obj];
[resDic setObject:obj forKey:keyArr[i]];
}
return resDic;
}
//将NSDictionary中的Null类型的项目转化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
NSMutableArray *resArr = [[NSMutableArray alloc] init];
for (int i = 0; i < myArr.count; i ++)
{
id obj = myArr[i];
obj = [self changeType:obj];
[resArr addObject:obj];
}
return resArr;
}
//将NSString类型的原路返回
//过滤掉诡异的"null"和"(null)"字符串
+(NSString *)stringToString:(NSString *)string
{
if ([string isEqualToString:@"null"] || [string isEqualToString:@"(null)"]) {
return @"";
}else{
return string;
}
}
//将Null类型的项目转化成@""
+(NSString *)nullToString
{
return @"";
}
#pragma mark - 公有方法
//类型识别:将所有的NSNull类型转化成@""
+(id)changeType:(id)myObj
{
if ([myObj isKindOfClass:[NSDictionary class]])
{
return [self nullDic:myObj];
}
else if([myObj isKindOfClass:[NSArray class]])
{
return [self nullArr:myObj];
}
else if([myObj isKindOfClass:[NSString class]])
{
return [self stringToString:myObj];
}
else if([myObj isKindOfClass:[NSNull class]])
{
return [self nullToString];
}
else
{
return myObj;
}
}
@end
AFN过滤处理
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"http://www.mocky.io/v2/58996b8b0f00007a011f4a9e" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// 过滤前
NSLog(@"过滤前----%@",responseObject);
// 过滤后
NSLog(@"过滤后---%@",[Util nullDic:responseObject]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
结果