gpt4 book ai didi

php - JSON 解析 --> Swift | JSON 写入中的顶级类型无效

转载 作者:行者123 更新时间:2023-11-30 12:48:38 25 4
gpt4 key购买 nike

我正在尝试使用 Swift 从 PHP 文件中检索信息。我在网上看到我应该使用JSON解析(我认为它被称为)。所以我在网上搜索并找到了一些信息,导致我得到以下代码:

func dataOfJson(urlString: String) -> NSArray{
let url = NSURL(string: urlString);
if (url != nil)
{
let data = NSData(contentsOf: url as! URL);
if (data != nil)
{
return try! JSONSerialization.data(withJSONObject: data as Any) as AnyObject! as! NSArray;
}else{
//return "Error -> Data is nil!";
return try! JSONSerialization.data(withJSONObject: data as Any) as AnyObject! as! NSArray;
}
}else{
return ["Error -> url is empty!"] as NSArray;
}
}

我这样调用上面的函数:print(dataOfJson(urlString: "some url/test.php"));

我调用的 URL 包含以下 PHP 代码:

<?php   
header("Content-Type: application/json");
require "dbconnect.php";
global $connect;
$result = array();
$temp = array();

if ($connect){
$fetch_data = mysqli_query($connect,"select * from dedi");

while ( $row = $fetch_data->fetch_object() ){
$temp = $row;
array_push($result,$temp);
}

echo json_encode($result);
return json_encode($result);
}
else{
echo json_encode("Something went wrong");
return json_encode("Something went wrong!");
}
mysqli_close(); ?>

遗憾的是,当我尝试运行该项目时,出现以下错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

我完全不知道如何修复它,是的,我在网上搜索并发现了类似的解决方案问题,但我无法理解这些问题,并且某些修复并没有改变任何内容......

最佳答案

documentation of NSJSONSerialization指出了 PHP 脚本中的 JSON 可能并不总是符合的一些要求:

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

关于php - JSON 解析 --> Swift | JSON 写入中的顶级类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299875/

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