When working with JSON data, I try to be very careful. Say I have JSON deserialized in an NSDictionary. In doing so, I need to pull the string associated with the URL key from the dictionary and turn it into NSURL. Also, I'm not 100% sure about JSON or string value.
I would do something like this:
NSURL *URL = nil; id URLObject = [JSON valueForKey:@"URL"]; if ([URLObject isKindOfClass:[NSString class]] && [URLObject length] > 0) { URLObject = [URLObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; URLObject = [URLObject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; URL = [NSURL URLWithString:URLObject]; }
After that, the URL will have a null or valid URL. -isKindOfClass: preempts the value of NSDictionary, NSArray, NSNumber, or NSNull. -length> 0 filters out an empty string (which, as you know, can ruin NSURL). Additional paranoia of decoding and then re-encoding of URL screens processes partially encoded URLs.
source share