Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore specific values when applying json_encode to class

Tags:

json

php

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

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??

like image 260
Marc HPunkt Avatar asked Feb 20 '14 21:02

Marc HPunkt


People also ask

What is the difference between json_encode and json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is Json_force_object?

JSON_FORCE_OBJECT (int) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. JSON_NUMERIC_CHECK (int) Encodes numeric strings as numbers.


1 Answers

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.

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.

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

DEMO: https://eval.in/103959

Note: This only works on PHP 5.4+

like image 171
Rocket Hazmat Avatar answered Sep 28 '22 19:09

Rocket Hazmat