#import "JSONRPC.h" @interface TestClass : NSObject <JSONRPCErrorHandler> -(void)testIt; @end
#import "TestClass.h" #import "Person.h" @implementation TestClass -(void)testIt { JSONRPCService* service = [[[JSONRPCService alloc] initWithURL:kServiceURL version:JSONRPCVersion_1_0] autorelease]; [[service callMethodWithNameAndParams:@"getUserDetails",@"user1234",nil] setDelegate:self callback:@selector(methodCall:didReturnUser:error:) resultClass:[Person class]]; // will convert the returned JSON into a Person object (providing that the class Person respond to -initWithJson, this is the case below) } -(void)methodCall:(JSONRPCMethodCall*)meth didReturnUser:(Person*)p error:(NSError*)err { // We will effectively receive a "Person*" object (and not a JSON object like a NSDictionary) in the parameter p // because we asked to convert the result using [Person class] in -testIt NSLog(@"Received person: %@",p); if (error) NSLog(@"error in method call: %@",err); } -(BOOL)methodCall:(JSONRPCMethodCall*)meth shouldForwardConnectionError:(NSError*)err { // handle the NSError (network error / no connection, etc.) return NO; // don't call methodCall:shouldForwardConnectionError: on the JSONRPCService's delegate. } @end
Used in TestClass as the result is converted into a Person object ("... resultClass:[Person class]")
@interface Person : NSObject { NSString* firstName; NSString* lastName; } -(void)initWithJson:(id)jsonObj; @property(nonatomic,retain) NSString* firstName; @property(nonatomic,retain) NSString* lastName; @end
#import "Person.h" @implementation Person @synthesize firstName,lastName; -(id)initWithJson:(id)jsonObj { if (self = [super init]) { self.firstName = [jsonObj objectForKey:@"firstname"]; self.lastName = [jsonObj objectForKey:@"lastname"]; } return self; } -(NSString*)description { return [NSString stringWithFormat:@"<Person %@ %@>",firstName,lastName]; } -(void)dealloc { [firstName release]; [lastName release]; [super dealloc]; } @end