PHP / IOS: what is the best way to code json for a web service?

I am trying to create a web service that serves json from mysql database via php to display in an iPhone application.

I have a standard mysql / php setup.

The data is in a table with fields and records. It queries sql to create a recordset. Each record in a recordset is a row.

php

$sql = "SELECT userid,task,longtask FROM tasks WHERE userid = 1 LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());  
$tasks = array();
while($row = mysql_fetch_assoc($res)) {
$tasks[] = array('row'=>$row);
 } 
echo json_encode(array('tasks'=>$tasks));
//

The web service produces the following output:

{"tasks":[{"row":{"userid":"1","task":"send email to Bob","longtask":"include attached memo"}}]}

However, I have a lot of problems reading this on iOS, suggesting that there might be a better format for the web service.

The structure is different from the structure in textbooks and other sources that I found for reading json in IOS (none of which use php / mysql).

- json , , , json iOS, , .

, , : 0

      NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                         options:kNilOptions 
                                                           error:&error];
    NSLog(@"about to print json: %@",json);
NSMutableArray *getElement = [json objectForKey:@"tasks"];
    for (NSDictionary *dict in getElement) {
        NSArray *array = [dict objectForKey:@"row"];
        NSString *str = [array objectAtIndex:0];
    }

.

+4
1

1: PHP

0 , PHP mysql_fetch_assoc.

mysql_fetch_array , .

$sql = "SELECT userid,task,longtask FROM tasks WHERE userid = 1 LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());  
$tasks = array();
while($row = mysql_fetch_array($res)) {
    $tasks[] = array('row'=>$row);
} 
echo json_encode(array('tasks'=>$tasks));

{"tasks":[{"row":{"0":"1","userid":"1","1":"send email to Bob","task":"send email to Bob","2":"include attached memo","longtask":"include attached memo"}}]}

0 userid.

2: iOS

iOS. .

NSString *str = [array objectForKey:@"userid"];`
+1

All Articles