Skip to content

Instantly share code, notes, and snippets.

Created June 28, 2011 21:51
Show Gist options
  • Save vgrichina/1052330 to your computer and use it in GitHub Desktop.
Save vgrichina/1052330 to your computer and use it in GitHub Desktop.
Three20 JSONP parser
#import <extThree20JSON/extThree20JSON.h>
#import <extThree20JSON/NSObject+SBJSON.h>
@interface JSONPResponse : TTURLJSONResponse {
#import "JSONPResponse.h"
#import <Three20Core/Three20Core.h>
@implementation JSONPResponse
// This method is based on the same-named method in TTURLJSONResponse
// Note, that only SBJSON suport is left
- (NSError *) request: (TTURLRequest *) request processResponse: (NSHTTPURLResponse *) response
data: (id) data {
// This response is designed for NSData objects, so if we get anything else it's probably a
// mistake.
TTDASSERT([data isKindOfClass: [NSData class]]);
TTDASSERT(nil == _rootObject);
NSError *err = nil;
if ([data isKindOfClass: [NSData class]]) {
NSString *json = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
// Remove JSONP wrapper
json = [json stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSRange openingBracket = [json rangeOfString: @"("];
NSRange closingBracket = [json rangeOfString: @")" options: NSBackwardsSearch];
if (openingBracket.location != NSNotFound && closingBracket.location != NSNotFound) {
json = [json substringWithRange:
NSMakeRange(openingBracket.location + 1, closingBracket.location - openingBracket.location - 1)];
// Parse JSON
_rootObject = [[json JSONValue] retain];
// Report error if failed to parse
if (!_rootObject) {
err = [NSError errorWithDomain: kTTExtJSONErrorDomain
code: kTTExtJSONErrorCodeInvalidJSON
userInfo: nil];
return err;
Copy link

Make sure you check my blog post about it –

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment