2016-12-23 31 views
0

我试图使用Swift从PHP文件中检索信息。我在网上看到我应该使用JSON解析(我认为它被称为)。所以,我搜索,发现了一些在线信息导致我下面的代码:JSON解析 - > Swift | 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' 

我完全不知道如何修复它,是的,我在网上搜索,发现类似的解决方案的问题,但我不明白这些和一些修复只是没有改变任何东西...

+0

1. MySQLi连接从未关闭。 2.不需要'返回json_encode(...);'。你应该'退出()'而不是。 3.您应该为JSON数据使用适当的Content-Type,即header('Content-Type:application/json');'。 4.然而,问题的根源很可能是Swift代码中的某处。 –

回答

0

The 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.
+0

我的PHP似乎没问题,但我认为问题来自swift ...我的swift上面有什么错误吗? – Nobody