Let's say we have a simple object to serialize with a nested object:
class User implements \JsonSerializable
{
private $name;
private $email;
private $address;
public function jsonSerialize()
{
return [
'name' => $this->name,
'email' => $this->email,
'address' => $this->address
];
}
}
The nested object:
class Address implements \JsonSerializable
{
private $city;
private $state;
public function jsonSerialize()
{
return [
'city' => $this->city,
'state' => $this->state
];
}
}
We use json_encode()
to serialize, this will use natively JsonSerializable::jsonSerialize():
$json = json_encode($user);
If $name
and $state
are null, how to get this:
{
"email": "john.doe@test.com",
{
"city": "Paris"
}
}
instead of this:
{
"name": null,
"email": "john.doe@test.com",
{
"city": "Paris",
"state": null
}
}