First JSON Iphone application

So now that we have the basics of installing JSON to our project, lets make a test application.

I started by creating a new project and used the Navigation Controller Template.

The first thing you want to do is setup your JSON environment as explained in the previous post and again you can visit the link above for instructions on how to do that.

Once it is setup you are ready to code. So the first thing is open up RootViewController.m and we need to import the JSON header so we can access it.

#import <JSON/JSON.h>

You need to synthesize the jsonArray

@synthesize jsonArray;

Now you want to edit the viewDidLoad function and make it look like this

- (void)viewDidLoad {
	// Add the following line if you want the list to be editable
	// self.navigationItem.leftBarButtonItem = self.editButtonItem;

	// init the url
	NSURL *jsonURL = [NSURL URLWithString:@"http://iphone.zcentric.com/test-json.php"];
	/*
	 loading the contents of the URL into a string. At this point we should hit
	 the json endpoint and put the contents of it in jsonData.
	*/
	NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];

	/*
	 we can verify the contents by looking at a NSLog if we open the console
	*/
	//NSLog(jsonData);

	// converting the json data into an array
	self.jsonArray = [jsonData JSONValue]; 

	// this will return the array.. in the console it will still look a bit like json
	// but that is a array object.
	//NSLog(@"%@", jsonArray);

	// this will give the current count
	//NSLog(@"count is: %i", [self.jsonArray count]);

	// releasing the vars now
	[jsonURL release];
	[jsonData release];
}

I hope I gave good comments in the code. Basically what we are doing is loading a url and placing the contents into a string and then using json to turn it into an array object that we can use later.

Now my array in PHP looks like this

$array = array(
        0       => 'http://iphone.zcentric.com/files/1.jpg',
        1       => 'http://iphone.zcentric.com/files/2.jpg',
        2       => 'http://iphone.zcentric.com/files/3.jpg',
        3       => 'http://iphone.zcentric.com/files/4.jpg',
);

I use 0-3 as keys to make it easy to load the values into a new row.

Now we need to tell the application how many rows we have

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [jsonArray count];
}

Then in the cellForRowAtIndexPath function above the return cell we want to set the text.

cell.text = (NSString *)[self.jsonArray objectAtIndex:indexPath.row];

Now we want to free the memory

- (void)dealloc {
	[jsonArray dealloc];
	[super dealloc];
}

Now we are done with this file so save it and close it and open up RootViewController.h. You want it to look like this

#import 

@interface RootViewController : UITableViewController {
	NSMutableArray *jsonArray; // added this
}

@property (nonatomic, retain) NSMutableArray *jsonArray;  // added this

@end

You should know to do this by now.

Once you are done you should be able to compile your application and see 4 rows. Also feel free to use my test-json.php endpoint since I know it works.

The source code is right here. Have fun!

About mike
Currently works for Recurly as a Senior Linux Admin. He has a wonderful wife Thanuja and 2 great children (Anusha and Brandon). His major side project is Photoblog.

Comments

12 Responses to “First JSON Iphone application”
  1. Anonymous says:

    Can you please explain what this does “JSONValue” in the line self.jsonArray = [jsonData JSONValue]; ?

  2. mikezupan says:

    the JSONValue method takes a json encoded string and turns it into variables objective C can read. So it will data into like

    NSDictionary
    NSArray
    NSString
    etc.

    Its all based on what the json encoded string is

  3. Geetha says:

    Hi
    i want to parse some complicate json file. how do i do? here i gave one example of my json file

    {
    list:{
    videos:[

    {
    started:'true',
    comments:'my video 1',
    timestamp:100000,
    id:206551212,
    name:'MYVideo',
    date:'Fri Jun 22',
    time:'1:05 pm',
    length:0.58

    },
    {
    started:'true',
    comments:'my video2 ',
    timestamp:100000,
    id:206551212,
    name:'MYVideo',
    date:'Fri Jun 22',
    time:'1:05 pm',
    length:0.58
    }
    ]
    }
    }

    and please make sure my JSON is correct or not.

    Thanks in Advance

  4. Armin says:

    I have also documented how to use the JSON framework for the iPhone. Beware that there is a problem since SDK 2.2. Check out the fix on http://jtribe.blogspot.com/2008/12/json-framework-with-iphone-sdk-22.html

  5. Good example and series, but a minor err sneaked in the above example: the NSURL created with URLWithString is autoreleased, so the [jsonURL release] will cause a crash.

  6. Douglas says:

    Why do you import a .php file format with json data in it as opposed to a .json file format?

  7. SQlclass3 says:

    Nice example i like this…..

  8. SQlclass3 says:

    Nice application.. i like that

  9. mahesh says:

    is it same for getting the image from the json responce?

  10. Hey
    I want to parse : {“id”:”agpmb3JzYS10ZXN0ch0LEghSZXRhaWxlchiPpgMMCxIGT3V0bGV0GOkHDA”,
    “address”:”41 Abdel Hamid Badawy St.”,
    “retailer”:”KFC”,
    “lat”:30.11764,
    “lon”:31.34869,
    “phone”:”02-26241292″,
    “icon”:”/api/image/serve?id=agpmb3JzYS10ZXN0cg0LEgVJbWFnZRipxQMM”}

    but when writing [json_string JsonValue] : I get error
    anyone help me???

Trackbacks

Check out what others are saying about this post...
  1. [...] Iphone Noob added an interesting post today on First JSON Iphone applicationHere’s a small reading … com/files/1. jpg’, 1 = ‘http://iphone. zcentric…. … com/files/2. jpg’, 2 = ‘http://iphone. zcentric…. … com/files/3. jpg’, 3 = ‘http://iphone. zcentric….$array = array( 0 = ‘http://iphone. zcentric…. [...]

  2. [...] a POST of image/metadata to tumblr (easy to migrate to another receiving server) Using JSON in Obj-C/iPhone Learn Obj-C Shortlist Nick Myer’s Tutorials Simple linking to MP3 streaming content [...]



Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

css.php