使用Alamofire从PHP服务器检索JSON时出现问题
发送数组时,我在服务器中检索到错误的JSON: 客户端对象:使用Alamofire从PHP服务器检索JSON时出现问题,php,ios,swift,alamofire,Php,Ios,Swift,Alamofire,发送数组时,我在服务器中检索到错误的JSON: 客户端对象: class Dummy : Mappable { var test1 = "test1"; var test2 = "test2"; func mapping(map: Map) { test1 <= map["test1"] test2 <= map["test2"] } required init(){} } 客户端打印(看起来还可以): 服
class Dummy : Mappable {
var test1 = "test1";
var test2 = "test2";
func mapping(map: Map) {
test1 <= map["test1"]
test2 <= map["test2"]
}
required init(){}
}
客户端打印(看起来还可以):
服务器实现(PHP):
响应服务器:
Array
(
[again_right] => Array
(
[dummy2] => Array
(
[test2] => test2
[test1] => test1
)
[dummy1] => Array
(
[test2] => test2
[test1] => test1
)
)
[again_wrong] => Array
(
[0] => Array
(
[test2] => test2
)
[1] => Array
(
[test1] => test1
)
[2] => Array
(
[test2] => test2
)
[3] => Array
(
[test1] => test1
)
)
[right] => Array
(
[test2] => test2
[test1] => test1
)
[wrong] => Array
(
[0] => Array
(
[test2] => test2
)
[1] => Array
(
[test1] => test1
)
[2] => Array
(
[test2] => test2
)
[3] => Array
(
[test1] => test1
)
)
)
正如您所看到的,数组中的对象是按它们的子对象数分割的,这与字典中的对象是不一样的。在您的日志中,我们看到了来自iOS端和PHP端的数据,但我们无法真正说出实际传输的是什么。我们必须看到问题实际发生在哪一方,所以看看是否可以打印出正在发送的实际HTTP请求。如果JSON错误,则iOS端错误,否则PHP读取错误 首先,确保将参数作为JSON发送到服务器。默认情况下,Alamofire将默认为URL编码,除非您指定需要JSON 接下来,看起来您正在打印
$\u POST
,这表明您可能将数据作为URL编码的参数而不是JSON发送。那可能把事情搞砸了
如果Alamofire以JSON的形式发送数据,而您在服务器上没有获得任何数据,那么请确保将其更改为读取包含JSON数据的HTTP正文:
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE );
我认为这可能涵盖了你的基础,或者至少给你一个好的开始,让你知道在哪里可以找到:)file\u get\u contents('php://input'); 是的,当我将编码更改为JSON时,我将获得数据。Thx youbtw,是什么原因导致我可以检索文章中以.JSON格式发送的内容,但我可以用file_get_contents检索它?以
.JSON
格式发送,将其格式化为实际的JSON格式,而不是URL编码的格式——这就是破坏原始JSON的原因。当您使用file\u get\u contents
获取数据时,您正在读取实际的HTTP请求正文,而不仅仅是参数——将其更改为JSON changed,其中数据存储在HTTP请求中。
ini_set("log_errors", 1);
ini_set("error_log", "$root/php-error.log");
error_log(print_r($_POST, true));
Array
(
[again_right] => Array
(
[dummy2] => Array
(
[test2] => test2
[test1] => test1
)
[dummy1] => Array
(
[test2] => test2
[test1] => test1
)
)
[again_wrong] => Array
(
[0] => Array
(
[test2] => test2
)
[1] => Array
(
[test1] => test1
)
[2] => Array
(
[test2] => test2
)
[3] => Array
(
[test1] => test1
)
)
[right] => Array
(
[test2] => test2
[test1] => test1
)
[wrong] => Array
(
[0] => Array
(
[test2] => test2
)
[1] => Array
(
[test1] => test1
)
[2] => Array
(
[test2] => test2
)
[3] => Array
(
[test1] => test1
)
)
)
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE );