How to ignore null property with JsonSerializable::jsonSerialize()?
<p>Let's say we have a simple object to serialize with a nested object:</p>

<pre><code>class User implements \JsonSerializable
{

    private $name;
    private $email;
    private $address;

    public function jsonSerialize()
    {
        return [
            'name'  =&gt; $this-&gt;name,
            'email'  =&gt; $this-&gt;email,
            'address' =&gt; $this-&gt;address
        ];
    }
}
</code></pre>

<p>The nested object:</p>

<pre><code>class Address implements \JsonSerializable
{

    private $city;
    private $state;

    public function jsonSerialize()
    {
        return [
            'city'  =&gt; $this-&gt;city,
            'state' =&gt; $this-&gt;state
        ];
    }
}
</code></pre>

<p>We use <code>json_encode()</code> to serialize, this will use natively  <a href="http://php.net/manual/en/jsonserializable.jsonserialize.php" rel="nofollow noreferrer">JsonSerializable::jsonSerialize()</a>:</p>

<pre><code>$json = json_encode($user);
</code></pre>

<p>If <code>$name</code> and <code>$state</code> are null, how to get this:</p>

<pre><code>{
    "email": "john.doe@test.com",
    {
        "city": "Paris"
    }
}
</code></pre>

<p>instead of this:</p>

<pre><code>{
    "name": null,
    "email": "john.doe@test.com",
    {
        "city": "Paris",
        "state": null
    }
}
</code></pre>