2012-01-08 57 views
8

有没有什么办法来控制json_encode对象的行为?就像排除空数组,空字段等一样?如何控制json_encode行为?

我意味着什么用serialize()时,在那里你可以实现神奇的__sleep()方法,并指定哪些属性应该被序列化,如:

class MyClass 
{ 
    public $yes = "I should be encoded/serialized!"; 
    public $empty = array(); // // Do not encode me! 
    public $null = null; // Do not encode me! 

    public function __sleep() { return array('yes'); } 
} 

$obj = new MyClass(); 
var_dump(json_encode($obj)); 

回答

0

你可以使私有变量。然后它们不会以JSON编码显示。

如果这不是一个选项,您可以创建一个私有数组,并使用魔术方法__get($ key)和__set($ key,$ value)来设置和从该数组中获取值。在你的情况下,键将是'空'和'空'。然后,您仍然可以公开访问它们,但JSON编码器不会找到它们。

class A 
{ 
    public $yes = "..."; 
    private $privateVars = array(); 
    public function __get($key) 
    { 
     if (array_key_exists($key, $this->privateVars)) 
      return $this->privateVars[$key]; 
     return null; 
    } 
    public function __set($key, $value) 
    { 
     $this->privateVars[$key] = $value; 
    } 
} 

http://www.php.net/manual/en/language.oop5.overloading.php#object.get

+0

是的,我知道,但感谢的答案。问题是当B扩展A时,B不能修改'$ privateVars'并使其成为'private'。 – gremo 2012-01-13 20:12:04

+1

会使它保护工作?为什么B将privateVars私有化,它已经是私有的了。 – Jarvix 2012-01-19 15:32:30

6

最正确的解决方案是延伸的接口JsonSerializable;

通过使用这个接口,你只需要与想要json_encode,而不是编码类什么样的功能jsonSerialize()返回。使用

你的例子:

class MyClass implements JsonSerializable{ 

    public $yes = "I should be encoded/serialized!"; 
    public $empty = array(); // // Do not encode me! 
    public $null = null; // Do not encode me! 

    function jsonSerialize() { 
      return Array('yes'=>$this->yes);// Encode this array instead of the current element 
    } 
    public function __sleep() { return array('yes'); }//this works with serialize() 
} 

$obj = new MyClass(); 
echo json_encode($obj); //This should return {yes:"I should be encoded/serialized!"} 

注:这部作品在PHP> = 5.4 http://php.net/manual/en/class.jsonserializable.php

+0

有了这个解决方案,当它们的值不是空数组或空值时,“empty”和“null”将不会被编码。我相信这不是提问者想要的。 – 2015-07-21 20:17:22