我使用下面的代码用空字符串替换json响应中的空值,但它不起作用。请帮我解决这个问题,我在许多场景和应用程序崩溃中从服务器响应中获取空值。
代码:
- (NSMutableDictionary *)recursive:(NSMutableDictionary *)dictionaryResponse {
NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]initWithDictionary:dictionaryResponse];
for (NSString *key in [dictionary allKeys]) {
id nullString = [dictionary objectForKey:key];
if ([nullString isKindOfClass:[NSDictionary class]]) {
[self recursive:(NSMutableDictionary*)nullString];
}else if([nullString isKindOfClass:[NSArray class]]){
for (int i=0; i<[nullString count]; i++) {
id nullstr = [nullString objectAtIndex:i];
if ([nullstr isKindOfClass:[NSDictionary class]]) {
[self recursive:(NSMutableDictionary*)nullstr];
}
}
}else {
if ((NSString*)nullString == (id)[NSNull null])
[dictionary setValue:@"" forKey:key];
}
}
return dictionary;
}
答案 0 :(得分:2)
试试这个:
- (NSMutableDictionary *)recursiveNullRemove:(NSMutableDictionary *)dictionaryResponse {
NSMutableDictionary *dictionary = [dictionaryResponse mutableCopy];
NSString *nullString = @"";
for (NSString *key in [dictionary allKeys]) {
id value = dictionary[key];
if ([value isKindOfClass:[NSDictionary class]]) {
dictionary[key] = [self recursiveNullRemove:(NSMutableDictionary*)value];
}else if([value isKindOfClass:[NSArray class]]){
NSMutableArray *newArray = [value mutableCopy];
for (int i = 0; i < [value count]; ++i) {
id value2 = [value objectAtIndex:i];
if ([value2 isKindOfClass:[NSDictionary class]]) {
newArray[i] = [self recursiveNullRemove:(NSMutableDictionary*)value2];
}
else if ([value2 isKindOfClass:[NSNull class]]){
newArray[i] = nullString;
}
}
dictionary[key] = newArray;
}else if ([value isKindOfClass:[NSNull class]]){
dictionary[key] = nullString;
}
}
return dictionary;
}
<强>编辑:强>
我在答案中找到了问题,现在已修复
这是支票代码:
NSDictionary *dict = @{@"1" : @{@"1.1": @"value", @"1.2" : [NSNull null]},
@"2" : @[@"2.1", @{@"2.2.1" : @"val", @"2.2.2" : [NSNull null]}],
@"3" : [NSNull null]};
dict = [self recursiveNullRemove:dict];
答案 1 :(得分:1)
这是从字符串中删除Null的简单方法
-(NSString *) removeNull:(NSString *) string
{
NSRange range = [string rangeOfString:@"null"];
if (range.length > 0 || string == nil) {
string = @"";
}
string = [self trimString:string];
return string;
}
-(NSString*) trimString:(NSString *)theString
{
NSString *theStringTrimmed = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
return theStringTrimmed;
}
答案 2 :(得分:-1)
if (![nullString isKindOfClass:[NSNull class]] )
{
return nullString;
}
else
{
return @"";
}