【问题标题】:Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0错误域 = NSCocoaErrorDomain 代码 = 3840 “字符 0 周围的值无效。” UserInfo={NSDebugDescription=字符 0 周围的值无效
【发布时间】:2018-02-20 20:20:35
【问题描述】:

enter image description herehere 我的 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。

【问题讨论】:

  • 你的问题是什么?
  • null 在 json 数组中返回。但使用相同的 url 我可以在浏览器上看到 json 数据
  • 您的 WS 返回的响应不是 JSON 有效的(我们在屏幕截图中看到的那个)。您可以在在线 JSON 验证器上对其进行测试,您会看到。这就是您出现此错误的原因。

标签: php ios objective-c json jsonparser


【解决方案1】:

首先,删除 PHP 代码中的“成功连接”文本。到目前为止,结果不是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);
}

【讨论】:

  • 这里是输出错误:错误域=NSCocoaErrorDomain 代码=3840“字符 0 周围的值无效。” UserInfo={NSDebugDescription=字符 0.} 周围的值无效。} json: (null)
  • @lived,太奇怪了,因为浏览器的结果不是json。我认为你需要改进它。
猜你喜欢
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 2018-06-17
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
相关资源
最近更新 更多