JSONkit and Exception handling
Having troubles with JSONKit and nil and null exceptions in occasions you can’t understand? This thing happened to me when trying to use something like “self.textview.text = [dictionary valueForKey:@”someKey”];” and I couldn’t understand why I kept receiving extensions about mismatch of the classes and NULL.
Well, the answer is that when JSONKit encounters a value that is NULL, it tries to translate it as accurately as it can to a value of NSDictionary. The correct equivalent would be “nil” but you can’t have an NSDIctionary holding a nil value, so JSONKit uses NSNull. So, when accessing NSDictionary values coming from a JSON source, you need to check for this probability too.
- (id)jsonFixedValueForKey:(NSString *)key
{
id value = [self valueForKey:key];
BOOL isNULLorNil = NO;
if (value != nil) {
if ([value isKindOfClass:[NSNull class]]) {
isNULLorNil = YES;
}
}else{
isNULLorNil = YES;
}
if (isNULLorNil) {
return nil;
}
return value;
}
Just place the above code to a new category for NSDictionary and then use something like “[dict jsonFixedValueForKey:@”someKey”]” and now you will receive a nil where the JSON originally had “null”, or you will have the value that this key represents, no matter the class.