0

Basically I have a JSON array on a webpage, the array works fine on the webpage and I can pull it into objective-c as a string, but I need to pull it into objective-c as an array. Can anybody tell me the most basic way to do this? I've seen some tutorials that do this but most of them are arrays of objects in JSON.

Here's my objective-c code to pull the information as a string is:

//create string to contain URL address for PHP file, the file name is index.php and the parameter: name is passed to the file
NSString *strURL = [NSString stringWithFormat:@"http://localhost:8888/page4.php?name=%@", _txtName.text];

//to execute PHP code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];

//to recieve the returned value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];


NSLog(@"%@", strResult);

Here is the PHP/JSON code for my webpage.

<?php

if (isset ($_GET["name"]))
        $name = $_GET["name"];
    else
        $name = "NULL";

// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM user WHERE name = '$name'")
or die(mysql_error());  
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );

$array = array(
"0" => $row['id'],
"1" => $row['name'],
);


$json_array = json_encode($array);
echo $json_array;

?>
Corey
  • 152
  • 1
  • 3
  • 11

2 Answers2

2

you can convert your json response to array using following code

    NSError* error = nil;
    NSArray *jsonArray = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          options:kNilOptions 
                          error:&error];
Dipen Panchasara
  • 13,480
  • 5
  • 47
  • 57
2

As of iOS 5, Apple provides a built-in class to do this for you. You can set options to make the returned NSArray and NSDictionary containers mutable, or the returned leaf objects mutable. It operates on NSData, rather than NSString. It's simple to use:

NSError *error = nil;
NSArray *parsedArray = [NSJSONSerialization JSONObjectWithData:dataUrl
                                                       options:kNilOptions
                                                         error:&error];
Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60