Print Shortlink

JSON data from NodeJS into iPhone app

Given below is a simple example of loading JSON data from a Node JS application into an iPhone application. The JSON data is serialized into a collection class.

The Node JS application is a http server implementation that returns a collection of countries in JSON format as response. The server.js file which can be run as “node server.js” from terminal window is shown below.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
}).listen(9090, '');
console.log('Server running at');

The Node JS application runs at http: The Objective-C code that sends a request to this URL, that loads the JSON data and deserializes it to a collection object is given below.

   NSURL* url = [[NSURL alloc]initWithString:@""];
   NSData* nsdata = [[NSData alloc]initWithContentsOfURL:url];
   NSError* error;
   id obj =[NSJSONSerialization JSONObjectWithData:nsdata options:kNilOptions error:&error];
   if([obj isKindOfClass:[NSDictionary class]]){
        NSDictionary* dict = obj;
        NSLog(@"Count: %d",[dict count]);
        NSLog(@"Name: %@, Population: %@",[dict objectForKey:@"name"],[dict objectForKey:@"population"]);
        NSArray* arr = obj;
        for (int i=0; i<[arr count]; i++) {
            NSDictionary* dict = [arr objectAtIndex:i];
            NSLog(@"Name: %@, Population: %@",[dict objectForKey:@"name"],[dict objectForKey:@"population"]);

In the application that we were building, the JSON data was either an array of countries or just a country instance alone. For this reason, you can see the use of ‘isKindOfClass‘ function used to cast the JSON data to NSArray or NSDictionary object.

Leave a Reply