PHP json_encode返回空的scstructure


PHP json_encode returning empty sctructure

我调用json_encode将对象数组发送回用户,在代码的其他部分,它可以正常工作,但在这一部分,它返回一个空的结构字符串。

以下是编码前在数组上调用json_encode的结果:

array(3) {
  [0]=>
  object(MinaProxy)#5 (7) {
    ["carregado":"MinaProxy":private]=>
    bool(true)
    ["link":"MinaProxy":private]=>
    int(1)
    ["idMina":protected]=>
    int(1)
    ["qntOuro":protected]=>
    int(2000)
    ["x":protected]=>
    int(307)
    ["idPartida":protected]=>
    int(1)
    ["proximo":protected]=>
    int(1)
  }
  [1]=>
  object(MinaProxy)#6 (7) {
    ["carregado":"MinaProxy":private]=>
    bool(true)
    ["link":"MinaProxy":private]=>
    int(2)
    ["idMina":protected]=>
    int(2)
    ["qntOuro":protected]=>
    int(2000)
    ["x":protected]=>
    int(512)
    ["idPartida":protected]=>
    int(1)
    ["proximo":protected]=>
    int(2)
  }
  [2]=>
  object(MinaProxy)#7 (7) {
    ["carregado":"MinaProxy":private]=>
    bool(true)
    ["link":"MinaProxy":private]=>
    int(3)
    ["idMina":protected]=>
    int(3)
    ["qntOuro":protected]=>
    int(2000)
    ["x":protected]=>
    int(716)
    ["idPartida":protected]=>
    int(1)
    ["proximo":protected]=>
    NULL
  }
}

以下是json_encode之后的结果:

[{},{},{}]

可以注意到,原始数组中没有特殊字符,所以我不认为这是编码问题。这是我调用json_encode的代码:

elseif($dados['acao'] == 'recuperarMinas') {
    $i = 0;
    $array = array();
    while ($this->partida->minas->temProximo()) {
        $array[$i] = $this->partida->minas->getProximoAvancando();
        $array[$i]->getIdPartida();
        $i++;
    }
    $_SESSION['partida'] = $this->partida;
    $retornoJson = json_encode($array);
    return $retornoJson;
}

问题是您的输出有三个具有私有和受保护属性的对象。

参见此示例

<?php
class sampleClass
{
    private $hello = 25;
}

$class = new sampleClass();
echo json_encode($class);
?>

输出将为{}

在您的例子中,您有三个{}对象的数组[],它们是空的,因为它们的所有属性都是私有的或受保护的。

但如果您将对象属性更改为公共属性,public $hello = 25;,则输出将为

{"hello":25}

您有受保护的和私有的属性,所以您不能使用任何函数,包括json_encode()来直接访问对象的属性。

使用JSONSerialize

这是因为它们不是公共的。如果你想要json_encode私有/受保护的变量,你必须自己实现json序列化。

您可以尝试谨慎考虑jsonserializable(php 5.4+)!!!!!!!假设您希望在响应某些http请求时序列化对象的私有/受保护属性,但在其他情况下,您可能不希望序列化这些属性,或者您可能已经运行了假定它们不是的代码(甚至是第三方)

无论如何,如果你想公开对象的所有属性,函数中的代码可以是这样的:

public function somethinghere() {
    return get_object_vars($this);
}

函数的完整签名被故意省略了,因为你应该根据你的上下文来决定你想做什么(在发布之前我有一些考虑,但我希望这样可以尽量减少批评)这个例子也可能被认为是糟糕的,因为它暴露了一切(您可以考虑创建一个只包含要公开的属性的关联数组)

工作示例