My class implements the
jsonSerialize in php
Then my class implements the jsonSerialize method and returns get_object_vars($this).
public function JsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
The problem with this is it returns all the values including NULL variables too. How can I only get the non-null variables as json-output?
Pass $vars
to function array_filter()
. If you don't provide it a callback, it will remove everything that is equivalent with FALSE
public function JsonSerialize()
{
$vars = array_filter(get_object_vars($this));
return $vars;
}
If you need to remove only the NULL
properties and keep other FALSE
-like values (empty strings, zeroes etc) then you need to write a function that decide what to keep and what to remove:
public function JsonSerialize()
{
$vars = array_filter(
get_object_vars($this),
function ($item) {
// Keep only not-NULL values
return ! is_null($item);
}
);
return $vars;
}
Just filter the $vars
vor null values:
<?php
public function JsonSerialize()
{
$vars = get_object_vars($this);
return array_filter($vars, function ($value) {
return null !== $value;
});
}