如何使用JsonSerializable :: jsonSerialize()忽略null属性? [英] How to ignore null property with JsonSerializable::jsonSerialize()?

查看:999
本文介绍了如何使用JsonSerializable :: jsonSerialize()忽略null属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
        ];
    }
}

嵌套对象:

class Address implements \JsonSerializable
{

    private $city;
    private $state;

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

我们使用json_encode()进行序列化,这将原生使用 JsonSerializable :: jsonSerialize( ):

We use json_encode() to serialize, this will use natively JsonSerializable::jsonSerialize():

$json = json_encode($user);

如果$name$state为空,如何获得此值:

If $name and $state are null, how to get this:

{
    "email": "john.doe@test.com",
    {
        "city": "Paris"
    }
}

代替此:

{
    "name": null,
    "email": "john.doe@test.com",
    {
        "city": "Paris",
        "state": null
    }
}

推荐答案

array_filter包装在返回的数组周围,例如

wrap array_filter around the returned arrays, e.g.

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

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

This will strip any entries equal to false (loosely compared), which includes any null values, but also 0s and false. If you need strict, e.g. only nulls, supply the following callback:

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

请参见 array_filter 的文档:

See the documentation for array_filter:

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

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

遍历数组中的每个值,将它们传递给回调函数.如果回调函数返回true,则将数组中的当前值返回到结果数组中.数组键会保留.

Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

另一种选择是使用 JMX序列化器,它是针对JSON,XML和YAML.不过要重得多.有关详细信息,请参见在JMS序列化器中排除空属性.

Another option would be to use JMX Serializer which is a highly configurable serializer for JSON, XML and YAML. It's much heavier though. See Exclude null properties in JMS Serializer for details.

这篇关于如何使用JsonSerializable :: jsonSerialize()忽略null属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆