如何使用 JsonSerialized::jsonSerialize() 忽略 null 属性?

2024-02-02

假设我们有一个简单的对象可以使用嵌套对象进行序列化:

class User implements \JsonSerializable
{

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

    public function jsonSerialize()
    {
        return [
            'name'  => $this->name,
            'email'  => $this->email,
            'address' => $this->address
        ];
    }
}

嵌套对象:

class Address implements \JsonSerializable
{

    private $city;
    private $state;

    public function jsonSerialize()
    {
        return [
            'city'  => $this->city,
            'state' => $this->state
        ];
    }
}

We use json_encode()序列化,这将在本机使用JsonSerialized::jsonSerialize() http://php.net/manual/en/jsonserializable.jsonserialize.php:

$json = json_encode($user);

If $name and $state为空,如何得到这个:

{
    "email": "[email protected] /cdn-cgi/l/email-protection",
    {
        "city": "Paris"
    }
}

而不是这个:

{
    "name": null,
    "email": "[email protected] /cdn-cgi/l/email-protection",
    {
        "city": "Paris",
        "state": null
    }
}

wrap array_filter围绕返回的数组,例如

public function jsonSerialize()
    return array_filter([
        'city'  => $this->city,
        'state' => $this->state
    ]);
}

这将删除任何等于 false(松散比较)的条目,其中包括任何空值,但也包括 0 和 false。如果您需要严格,例如仅空值,提供以下回调:

function($val) { return !is_null($val); }

请参阅文档array_filter http://php.net/array_filter:

(PHP 4 >= 4.0.6、PHP 5、PHP 7)

迭代数组中的每个值,将它们传递给回调函数。如果回调函数返回 true,则数组中的当前值将返回到结果数组中。数组键被保留。

另一种选择是使用JMX 串行器 http://jmsyst.com/libs/serializer这是一个高度可配置的 JSON、XML 和 YAML 序列化器。不过它重得多。看在 JMS 序列化器中排除 null 属性 https://stackoverflow.com/questions/36429671/exclude-null-properties-in-jms-serializer了解详情。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 JsonSerialized::jsonSerialize() 忽略 null 属性? 的相关文章

随机推荐