I\'m frequently finding the need to cache data structures created by NSJSONSerialization
to disk and as -writeToFile
fails if there are nulls, I ne
Here's the code I'm using to clean up my JSON calls, seems to work well but, since there's some processing overhead involved I really only use it in situations where I can't do the null handling on the server. NSNull crashes is far and away our biggest app crash problem.
+ (id)cleanJsonToObject:(id)data {
NSError* error;
if (data == (id)[NSNull null]){
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]]){
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else {
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = array.count-1; i >= 0; i--) {
id a = array[i];
if (a == (id)[NSNull null]){
[array removeObjectAtIndex:i];
} else {
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys]) {
id d = dictionary[key];
if (d == (id)[NSNull null]){
dictionary[key] = @"";
} else {
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else {
return jsonObject;
}
}
You call it by passing the NSData retrieved via NSURLConnection.
NSArray *uableData = [utility cleanJsonToObject:data];
or
NSDictionary *uableData = [utility cleanJsonToObject:data];