Do not show null element with Symfony serializer

✔ Recommended Answer

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>

Source: stackoverflow.com

Answered By: yceruto

 To exclude null elements when using the Symfony serializer, you can use the Symfony\Component\Serializer\Normalizer\AbstractNormalizer::IGNORED_ATTRIBUTES option.

php
use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; $data = [ 'foo' => null, 'bar' => 'hello', 'baz' => null, ]; $serializer = new Serializer([], [new \Symfony\Component\Serializer\Normalizer\ArrayDenormalizer()]); $serializedData = $serializer->serialize($data, 'json', [ AbstractNormalizer::IGNORED_ATTRIBUTES => function ($value, $key) { return $value === null; } ]); echo $serializedData; // {"bar":"hello"}
 
In this example, the IGNORED_ATTRIBUTES option is set to a closure that returns true if the value is null. This tells the serializer to ignore any attribute with a null value, resulting in only the bar attribute being serialized.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755