Instantly share code, notes, and snippets.

Embed
What would you like to do?
Three20 JSONP parser
#import <extThree20JSON/extThree20JSON.h>
#import <extThree20JSON/NSObject+SBJSON.h>
@interface JSONPResponse : TTURLJSONResponse {
}
@end
#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
@vgrichina

This comment has been minimized.

Owner

vgrichina commented Jun 29, 2011

Make sure you check my blog post about it – http://www.componentix.com/blog/21

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