如何控制json_encode行为?

时间:2012-01-08 13:41:53

标签: php object serialization json

有没有办法控制对象的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));

2 个答案:

答案 0 :(得分:5)

最正确的解决方案是扩展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!"}

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

答案 1 :(得分: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

相关问题