Created
June 28, 2011 21:51
-
-
Save vgrichina/1052330 to your computer and use it in GitHub Desktop.
Three20 JSONP parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <extThree20JSON/extThree20JSON.h> | |
#import <extThree20JSON/NSObject+SBJSON.h> | |
@interface JSONPResponse : TTURLJSONResponse { | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure you check my blog post about it – http://www.componentix.com/blog/21