Quote:
Originally Posted by dany_dev
that format is JSON, my advice is not to parse it with normal methods but using a framework that can easily do it, like SBJson
|
For something that simple, I think I'd avoid the overhead of including a JSON parser.
for the string:
Quote:
|
{ "kind": "urlshortener#url", "id": "http://goo.gl/something", "longUrl": "http://somethinglonggggg/" }
|
I'd use the NSString method rangeOfString: @"http://" to find the beginning of the URL, then search from that offset to the next quote, build an NSRange from the beginning of the "http" up to but not including the quote, and use substringWithRange to get the URL.
Something like this:
Code:
NSString* JSON_String = @"{ \"kind\": \"urlshortener#url\", \"id\": \"http://goo.gl/something\", \"longUrl\": \"http://somethinglonggggg/\" }";
NSRange urlRange;
//Find the location of the first @"http://" in the returned JSON string
urlRange = [JSON_String rangeOfString: @"http://"];
//Create a substring that discards everything before the "http"
NSString* trimmedString =
[JSON_String substringFromIndex: urlRange.location];
//Find the first quote after the "http"
urlRange = [trimmedString rangeOfString @"\""];
//Create the final string for the shortened URL.
NSString* theShortenedURL =
[trimmedString substringToIndex: urlRange.location];
The code above assumes that the shortened URL will always appear before the long URL in the JSON string. If that's not true you'd have to first search for urlshortener tag, then search from that point for the "http".
Disclaimer: The code above was thrown together in a couple of minutes and has not been compiled, much less tested. My code usually has a few syntax errors on the first pass. I'm a terrible proofreader. I can spot logic problems pretty quickly, but syntax errors are another story. The code above also doesn't include any error checking. That's left as an "exercise for the reader."