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.
//server.js var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('[{"name":"India","population":1212121213222},{"name":"USA","population":889632232}]'); }).listen(9090, '127.0.0.1'); console.log('Server running at http://127.0.0.1:9090/');
The Node JS application runs at http:127.0.0.1:9090/. 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:@"http://127.0.0.1:9090/"]; 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"]); } else{ 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.