2012-01-08 55 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