JSON RPC in Objective C

I am working on a side project for work using JSON RPC from an iPhone (Arista eAPI calls from an iPhone app), so I had to get familiar with using JSON RPC using the iOS Objective C libraries. Here’s a quick rundown of how it works:

There are two major components:
NSJSONSerialization – Converts JSON Data to Dictionaries/Arrays, and vice versa
NSURLConnection – Handles HTTP connection to the API server

First I create a NSMutableDictionary with all the keys/values that I want to encode into JSON to send to the server (or switch in this case). In this example, commands is an array of strings, specific to eAPI calls, and paramsDict puts the other eAPI wrappers around the API call. Then I wrap paramsDict inside the JSON RPC Request format, which is rpcDict:

    NSMutableDictionary *paramsDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"version",
                                       commands, @"cmds",
                                       @"json", @"format", nil];
    NSMutableDictionary *rpcDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"2.0", @"jsonrpc",
                                    @"runCmds", @"method",
                                    paramsDict, @"params",
                                    @"CapiExplorer-123", @"id", nil];

Now I take rpcDict, and serialize it into a NSData JSON object, the resulting jsonData is ready to be sent to the API server:

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:rpcDict options:NSJSONWritingPrettyPrinted error:&error];

Now I create the URL request that the application will use to make the RPC request. In this case I’m providing my username and password in the URL string, and _aristaSwitch.switchIP is an NSString containing the IP address of the switch. Also note that I needed to set the content type, and used the jsonData data object as the body:

    NSString *urlString = [NSString stringWithFormat:@"http://user:pass@%@/command-api",
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:jsonData];

Now I can make the connection, send the request, and start receiving a reply:

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection start];

Once I’ve sent the request, I need to then handle the data coming back from the server. To do this, I have the class implement NSURLConnectionDelegate and NSURLConnectionDataDelegate. These delegates handle the connection response, and downloading data. Now I implement the necessary functions, the first two handle the initial response and data stream. I’m using receivedData as a global variable to hold the data coming from the server:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    [self.receivedData setLength:0];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    // Append the new data to receivedData.
    [self.receivedData appendData:data];

The final method to implement takes care of the data once the connection has finished. Here I use NSJSONSerialization again to turn the received JSON data back into an NSDictionary that I can use.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
    NSError *error;
    NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"myDict %@ %@", myDictionary, error);
    connection = nil;
    self.receivedData = nil;

One thought on “JSON RPC in Objective C

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s