Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=字符 0 周围的值无效

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0

enter image description here这是我的 RetriveData.Php:

<?php
ini_set("display_errors","on");
include("connection.php");

$query= "SELECT * FROM Person" ; //replace  with your table name
$result = mysqli_query($con,$query)  or  die("Error".mysqli_error($con));
//create an array
$json = array();
if(mysqli_num_rows($result))
{
  while($row=mysqli_fetch_row($result))
   {
      $json[]=$row;
   }
}
  echo json_encode($json);
 ?>

这里是我的 .m 文件代码:

NSError *error = nil;
NSString *url_string = [NSString stringWithFormat: @"http://127.0.0.1/RetriveData.php"];
NSData *data = [url_string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@",error);
NSLog(@"json: %@", json);

问题是这个 json 数组打印 Null。

首先,删除 PHP 代码中的文本 "Successfully connect"。到目前为止,结果不是 json 格式。努力改进。

其次,在iOS这边,直接使用url字符串作为JSON。正确的方法是从url中获取数据,然后将其转换为JSON。尝试:

NSError *error = nil;
NSString *url_string = @"http://127.0.0.1/RetriveData.php";
NSURL *url = [NSURL URLWithString:url_string];
if (url != nil) {
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSLog(@"%@",error);
    NSLog(@"json: %@", json);
}