標籤:
後端返回的資料中總會出現一些NSNull類型,當我們一處理常式就會崩潰,因此想到把返回的資料中的NSNull類型全部轉換成@""Null 字元串。下面是轉化方法:
1 自訂的幾個方法:放在NSDictionary類別中
#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類型的原路返回
+(NSString *)stringToString:(NSString *)string
{
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;
}
}
2 使用方法(綠色的是實際用到的代碼)
(1)原始的json串:後端返回的json串裡麵包含類型NSString,NSArray,NSDictionary,NSNull類型。
{"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}}
(2)用SBJson庫:json串轉換成字典
NSDictionary *jsonDic = [retString JSONValue];
(3)用自訂方法轉換後的結果:將字典中所有的NSNull類型轉換成@""
NSDictionary *dict = [NSDictionary changeType:jsonDic];
{
"img_url" = "http://api.jgfw.me/assets/uploads/files/";
num = 3;
"order_info" = {
"order_no" = E15031267469289848688;
"order_state" = "";
"order_time" = "";
"pay_time" = "";
price = 0;
};
price = "";
"service_id" = "";
"service_info" = {
"customer_address" = "";
"customer_name" = "";
"customer_phone" = "";
lat = "";
lon = "";
"new_jishi" = "";
"old_jishi" = "";
"service_detail" = "";
"service_time" = "";
"service_type" = "";
};
"service_name" = "";
status = 1;
}
iOS開發解決json串中的NSNull類型