将json_encode应用于类时如何忽略特定值

时间:2022-03-15 15:36:06

Is there a way to ignore specific class attributes of a class in php when encoding to json.

有没有办法在编码为json时忽略php中类的特定类属性。

For example in java with the jackson library I can annotate globals with @JsonIgnore to achieve this. Is there anything comparable (preferably native) in php??

例如,在带有jackson库的java中,我可以用@JsonIgnore注释全局变量来实现这一点。在PHP中有什么可比的(最好是原生的)??

1 个解决方案

#1


5  

One method is to utilize the JsonSerializable interface. This lets you create a function that's called when json_encode() is called on your class.

一种方法是使用JsonSerializable接口。这使您可以创建在类上调用json_encode()时调用的函数。

For example:

class MyClass implements JsonSerializable{
    public $var1, $var2;

    function __construct($a1, $a2){
        $this->var1 = $a1;
        $this->var2 = $a2;
    }

    // From JsonSerializable
    public function jsonSerialize(){
        return ['var1' => $this->var1];
    }
}

So, when json_encode() is called, only var1 will be encoded.

因此,当调用json_encode()时,只会编码var1。

$myObj = new MyClass(10, 20);
echo json_encode($myObj); // {"var1":10}

DEMO: https://eval.in/103959

Note: This only works on PHP 5.4+

注意:这仅适用于PHP 5.4+

#1


5  

One method is to utilize the JsonSerializable interface. This lets you create a function that's called when json_encode() is called on your class.

一种方法是使用JsonSerializable接口。这使您可以创建在类上调用json_encode()时调用的函数。

For example:

class MyClass implements JsonSerializable{
    public $var1, $var2;

    function __construct($a1, $a2){
        $this->var1 = $a1;
        $this->var2 = $a2;
    }

    // From JsonSerializable
    public function jsonSerialize(){
        return ['var1' => $this->var1];
    }
}

So, when json_encode() is called, only var1 will be encoded.

因此,当调用json_encode()时,只会编码var1。

$myObj = new MyClass(10, 20);
echo json_encode($myObj); // {"var1":10}

DEMO: https://eval.in/103959

Note: This only works on PHP 5.4+

注意:这仅适用于PHP 5.4+