【问题标题】:Xcode parsing error of json returned from phpphp返回的json的Xcode解析错误
【发布时间】:2015-03-26 19:16:42
【问题描述】:

我正在尝试使用 PHP 从 MySQL 服务器获取数据。下面是PHP文件内容:

<?php 
header('Content-type: application/json; charset=utf-8');
$dbc=mysql_connect("host", "defaultuser", "defaultuser");
mysql_select_db("customer");
$query = "SELECT * FROM customer_infor";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result))
{
$id_index=$line['id_index'];
$first_name=$line['first_name'];
$last_name=$line['last_name'];

$customers[]=array('id_index'=>$id_index, 'first_name'=>$first_name, 'last_name'=>$last_name);

}
$response['customers']=$customers;

echo json_encode($response);
mysql_close($dbc);
?>

PHP脚本返回的json结果如下:

{"customers":[{"id_index":"1","first_name":"Michael","last_name":"Johnson"}, {"id_index":"2","first_name":"Bill","last_name":"Harrison"},{"id_index":"3","first_name":"Julie","last_name":"Johns"}]}

当我尝试使用 Xcode 接收 json 字符串并对其进行解析时,请使用以下代码:

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.connectionData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSString *retString = [[NSString alloc] initWithData:self.connectionData encoding:NSUTF8StringEncoding];    

    NSError *parseError = nil;

    self.dataArray = [NSJSONSerialization JSONObjectWithData:self.connectionData options:0 error:&parseError];
    if (!parseError) {

        NSLog(@"json array is %@", self.dataArray);
        [self.tableView reloadData];
    } else {
        NSString *err = [parseError localizedDescription];
        NSLog(@"Encountered error parsing: %@", err);
    }  
    connection = nil;
    self.connectionData = nil;
}

此 Xcode 脚本位于视图控制器中。返回json数据时,先放入self.connectionData,再由NSJSONSerialization解析。数据最终放入self.dataArray。 我期待三个客户的 dataArray 中有 3 个元素。但是,NSLog 和系统调试都仅指示数组中的一个元素。此错误使我无法进一步将客户数据放入表格视图中。

谁能帮我找到这个问题的解决方案?

【问题讨论】:

  • self.dataArray 是一个字典,它的valueForKey:@"customers" 是一个数组。
  • 或其objectForKey。或self.dataArray[@"customers"].
  • Xcode 只是一个花哨的编辑器/编译器。完成上述工作的是您的应用程序。

标签: php ios mysql objective-c json


【解决方案1】:

试试这个:

NSDictionary *dataReturned = [NSJSONSerialization JSONObjectWithData:self.connectionData options:0 error:&parseError];
self.dataArray = dataReturned[@"customers"];
if (!parseError) {

    NSLog(@"json array is %@", self.dataArray);
    [self.tableView reloadData];
} else {
    NSString *err = [parseError localizedDescription];
    NSLog(@"Encountered error parsing: %@", err);
}  

希望这会有所帮助.. :)

【讨论】:

  • 非常感谢,伙计!它完美无缺! NSDictionary 与 NSArray 总是让我感到困惑.....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 2015-03-06
  • 2014-07-18
  • 2012-05-14
  • 2013-12-20
  • 1970-01-01
相关资源
最近更新 更多