Skip to content

Using JSON Web Services and iPhone SDK

April 16, 2010

In this tutorial I will give a simple example using PHP (server-side scripting) to output some JSON on a web page, and I will also show how to grab the data online and parse it within the iPhone environment. I will be using the awesome JSON parsing framework called “SBJSON” available here.

Outputting JSON text is very easy within the PHP language on a server (this tutorial is not primarily focused on PHP, so if you do not have it installed on your server already, then I can’t help you there). The code should go something like this:

<?php

$output = array(

‘name’ => ‘Connor’,

‘description’ => ‘This is me’

);

echo json_encode($output);

?>

Essentially you can just define a PHP array (in a dictionary-like format or just non value-key pair format), and it is converted to JSON with the json_encode() function.

To start off in XCode, make sure that you have added the JSON framework files to your project. Then, ensure that the framework is imported to your View Controller or class that will be utilizing the JSON parsing capabilities.

#import “JSON.h”

Then, within a method of your choice (the place where you want to work with the online JSON data), use similar code to the following:

SBJSON *parser = [[SBJSON alloc] init]; —simple allocation and initialization of the SBJSON class

NSString *rawJSON = [[NSString alloc] initWithContentsofURL:[NSURL URLWithString:@”http://myurl.com/myjson.php”%5D%5D; —grab just the raw JSON string from our PHP file.

NSDictionary *jsonData = (NSDictionary *)[parser objectWithString:rawJSON error:nil]; —parse the JSON string into a dictionary (this could be in NSArray format as well if you structured your JSON data without the key-value pairs)

[parser release];

[rawJSON release];

After these steps are completed, you may iterate through or work with your parsed JSON as you would with any other dictionary or array within the Objective-C language.

Thanks for coming to my blog!

Advertisements

From → regular

2 Comments
  1. Margaret permalink

    Hi
    A question.. we can encode an array like a list and used it in the iphone?

    Example:
    $output = array(

    ‘user name 1’,

    ‘user name 2’,

    );

    echo json_encode($output);

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: