如何控制json_encode行为?

gre*_*emo 9 php serialization json object

有没有办法控制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));
Run Code Online (Sandbox Code Playgroud)

小智 6

最正确的解决方案是扩展JsonSerializable接口;

通过使用此接口,您只需要使用函数jsonSerialize()返回您希望json_encode编码而不是您的类.

使用你的例子:

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!"}
Run Code Online (Sandbox Code Playgroud)

注意:这适用于php> = 5.4 http://php.net/manual/en/class.jsonserializable.php


Jar*_*vix 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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