I used below code to replace nulls from json response with empty string, but it is not working. Please help me out to fix this issue, i am getting nulls from server response in lot of scenarios and App crashes.
Code:
- (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;
}
try this:
- (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;
}
EDITED:
I hase find the problem in my answer, and now it fixed
this is check code:
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];
here is simple method to remove the Null from the string
-(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;
}
if (![nullString isKindOfClass:[NSNull class]] )
{
return nullString;
}
else
{
return @"";
}