gpt4 book ai didi

php - Xcode解析php返回的json错误

转载 作者:行者123 更新时间:2023-11-29 23:08:34 24 4
gpt4 key购买 nike

我正在尝试使用 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 脚本位于 View Controller 中。返回json数据时,首先将其放入self.connectionData中,然后由NSJSONSerialization解析。数据最终被放入self.dataArray中。我预计 dataArray 中有 3 个元素,分别对应三个客户。然而,NSLog 和系统调试都只指示数组中的一个元素。此错误使我无法进一步将客户数据放入 TableView 中。

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

最佳答案

试试这个:

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);
}

希望这有帮助..:)

关于php - Xcode解析php返回的json错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com