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??
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.
The json_encode() function is used to encode a value to JSON format.
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.
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+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With