Do not show null element with Symfony serializer Do not show null element with Symfony serializer symfony symfony

Do not show null element with Symfony serializer


A solution would be to extend from ObjectNormalizer class, override the normalize() method and remove all null values there:

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;use Symfony\Component\Serializer\Serializer;use Symfony\Component\Serializer\Encoder\XmlEncoder;class CustomObjectNormalizer extends ObjectNormalizer{    public function normalize($object, $format = null, array $context = [])    {        $data = parent::normalize($object, $format, $context);        return array_filter($data, function ($value) {            return null !== $value;        });    }}$encoders = array(new XmlEncoder());$normalizers = array(new CustomObjectNormalizer());$serializer = new Serializer($normalizers, $encoders);// ...

If we have an array of Person like the one of the official documentation:

// ...$person1 = new Person();$person1->setName('foo');$person1->setAge(null);$person1->setSportsman(false);$person2 = new Person();$person2->setName('bar');$person2->setAge(33);$person2->setSportsman(null);$persons = array($person1, $person2);$xmlContent = $serializer->serialize($persons, 'xml');echo $xmlContent;

The result will be those not null nodes:

<?xml version="1.0"?><response>    <item key="0">        <name>foo</name>        <sportsman>0</sportsman>    </item>    <item key="1">        <name>bar</name>        <age>33</age>    </item></response>


There is a better solution also since November 2016 with this feature : [Serializer] XmlEncoder : Add a way to remove empty tags

You just have to put the context parameter remove_empty_tags to true like this example