[ACCEPTED]-Do not show null element with Symfony serializer-serialization

Accepted answer
Score: 12

A solution would be to extend from ObjectNormalizer class, override 3 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 2 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 1 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>
Score: 2

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

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

More Related questions