首页 \ 问答 \ 从php返回的json的Xcode解析错误(Xcode parsing error of json returned from php)

从php返回的json的Xcode解析错误(Xcode parsing error of json returned from php)

我正在尝试使用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和系统调试都只指示数组中的一个元素。 此错误阻止我进一步将客户数据放入表视图中。

任何人都可以帮我找到解决这个问题的方法吗?


I'm trying to use PHP to fetch data from a MySQL server. Below is the PHP file content:

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

The PHP script returned the json result as below:

{"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"}]}

When I try to use Xcode to receive the json string and parse it use the following code:

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

This Xcode script is in a view controller. When the json data is returned, it is firstly put into self.connectionData, which is then parsed by NSJSONSerialization. The data are finally put into self.dataArray. I was expecting that there are 3 elements in the dataArray, for the three customers. However, the NSLog and system debugging both indicate only one element in the array. This error prevents me from further putting the customer data into a table view.

Can anybody help me find the solution to this problem?


原文:https://stackoverflow.com/questions/28182940
更新时间:2022-09-21 22:09

最满意答案

尝试这个:

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

希望这可以帮助.. :)


Try this:

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

Hope this helps.. :)

相关问答

更多
  • 我已经通过用纯文本替换成功和错误消息解决了问题,事实上,我无法以我尝试的方式编码为json htlm标记 $result['success']=true; $msg = "ok"; $result['success_msg']=$msg; $result['success']=false; $msg="account already activated"; $result['error_msg']=$msg; echo json_e ...
  • 您正在使用空参数执行查询,因此您的网址http://www.photosbychristian.com/ems/countys.php?state=Pennsylvania将实际转变为http://www.photosbychristian.com/ems/countys.php?state=Pennsylvania? 返回 -
    Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000 ...
  • 尝试这个: NSDictionary *dataReturned = [NSJSONSerialization JSONObjectWithData:self.connectionData options:0 error:&parseError]; self.dataArray = dataReturned[@"customers"]; if (!parseError) { NSLog(@"json array is %@", self.dataArray); [self.tableVie ...
  • data已经是一个对象,不需要使用$.parseJSON(data) (它会导致错误,因为$.parseJSON需要一个字符串而不是一个对象作为参数) 还有什么:你不应该返回$ data(它包含所有用户的登录数据),而是返回$user 。 成功然后使用alert(h.username); data is already an object, there is no need for using $.parseJSON(data) (it will result in an error, because $. ...
  • 以下是两种(有几种)可能性: PHP选项: 处理NULL对象以使其提前解析... if ($mydata==NULL) { $mydata = new stdClass(); } echo json_decode($mydata); JS选项: 尝试在客户端解析时捕获错误。 // Catch the error try { var data = JSON.parse(json); } catch(error) { // Handle the error } Here are tw ...
  • 好的,在您的JSON中,前面有一个UTF-8 BOM。 你能找到以下区别: {"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null} 和: {"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"p ...
  • 一个更简洁的方法,就是这样: let json = "{\"item1\" : 1234, \"item2\" : 4567, \"item3\" : 78910, \"item4\" : 1234}" // simulated string response ... let data = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) // turn it into NSData if let JSONObj ...
  • 尝试先绑定另一个而不是DOM元素,如下所示: $('#otherDivContent').find('#title').html('

    test

    '); 其中#otherDivContent是您最初在页面上的div(或其他元素)。 Try to bind first in another not DOM element, something like this: $('#otherDivContent').find('#title').html('

    test

    '); Where #ot ...
  • 正如@barmar指出的那样,您的JSON数据格式不正确。 如果你已经有了正确的JSON格式,你可以使用它并通过foreach循环将它输出到表中。 考虑这个例子:
  • 您可能有一个不可打印的角色,但没有出现在您在问题中粘贴的内容中。 我将您的文本复制并粘贴到您提供的链接的在线解析器中,并且干净地解析。 尝试将原始文本复制并粘贴到此在线十六进制转储网站中 ,并与从上面的SO问题复制和粘贴时获得的内容进行比较...如果它们不同,那么您将了解伪造字符的位置。 这是我得到的输出的截图,它干净地解析。 You probably have a non printable character that is not showing up in what you pasted in yo ...

相关文章

更多

最新问答

更多
  • 关于计划在cuFFT中重用(On plans reuse in cuFFT)
  • 在类实例中调用getter时如何将列表作为字符串返回(How to return a list as a string when calling a getter in a class instance)
  • 电子邮件不是使用php发送的(Email is not sending using php)
  • 使用按钮来创建/追加数组(Use button to create/append array)
  • 如何获取字符数限制,包括默认名称-Reactjs(How to get character count limitation including default name-Reactjs)
  • 为什么NSMutableDictionary不想写入文件?(Why NSMutableDictionary don't want write to file?)
  • Swift删除宽高比约束(Swift remove aspect ratio constraint)
  • 与IE7 Angularjs的兼容性(Compatibility with IE7 Angularjs)
  • oracle查看text文件内容有哪些命令
  • 使用带有flex的minHeight会创建意外的填充(Using minHeight with flex creates unexpected padding)
  • text-align / align-content不起作用(text-align / align-content doesnt work)
  • 分层数据结构设计(嵌套集)(Hierarchical Data Structure Design (Nested Sets))
  • Riak Java HTTPClientAdapter TCP CLOSE_WAIT(Riak Java HTTPClientAdapter TCP CLOSE_WAIT)
  • 如果字段不是字符串,则将SqlDataReader字段强制转换为字符串(Cast SqlDataReader field to a string if the field is not a string)
  • 莱宁根新抛出异常(leiningen new throws exception)
  • 在javascript中修复不正确的转义字符串(fixing improperly escaped string in javascript)
  • Web Audio API参数调制在Safari中无法正常工作(Web Audio API parameter modulation not working in Safari)
  • 长沙岳麓区有没有书法培训学校?
  • pro/engineer视频教程下载
  • 九游游戏中心下载的安装包为什么安装不上
  • 外键问题(foreign key issue)
  • ASP.NET动态用户控件可以保存数据问题(ASP.NET Dynamic user controls save data issue)
  • 不确定如何使用FluentValidation测试此.NET字符串(Not sure how to test this .NET string with FluentValidation)
  • 最新时间从两个型号更新(Latest time updated from two models)
  • 扭曲的自定义CancelledError(Twisted custom CancelledError)
  • jQuery动画在Firefox中不起作用(jQuery animation not working in Firefox)
  • 通过Facebook登录评论社交插件不会触发事件?(Login via Facebook comments social plugin does not trigger an event?)
  • HttpWebRequest没有发布(HttpWebRequest not posting)
  • 更改Google Maps V2中的标记颜色(Change marker color in Google Maps V2)
  • ASP.Net下拉列表不会重新显示我选择的选项(ASP.Net Dropdown List Doesn't Re-Display My Selected Option)