title: Do not show null element with Symfony serializer
body: <p>So I have many classes I want to serialize with Symfony serializer. For instance</p>
  
  <pre><code>class Foo
  {
    public $apple = 1;
    public $pear = null;
  
    public function serialize() {
      Utils::serialize($this);
    }
  }
  </code></pre>
  
  <p>which I serialize with the following <code>serialize()</code> call :</p>
  
  <pre><code>class Utils {
      public static function serialize($object) {
        $encoder = new XmlEncoder();
        $normalizer = new ObjectNormalizer();
        $serializer = new Serializer(array($normalizer), array($encoder));
        $str = $serializer-&gt;serialize($object, 'xml')
      }
  }
  </code></pre>
  
  <p>The output produced gives me: </p>
  
  <pre><code>&lt;apple&gt;1&lt;/apple&gt;&lt;pear/&gt;
  </code></pre>
  
  <p>The output expected should be: </p>
  
  <pre><code>&lt;apple&gt;1&lt;/apple&gt;
  </code></pre>
  
  <p>I took a look at the <a href="http://symfony.com/doc/2.8/components/serializer.html" rel="nofollow noreferrer">Symfony 2.8 doc</a> and managed to find a quick solution by using <code>$normalizer-&gt;setIgnoredAttributes("pear")</code>.</p>
  
  <p>So the improved serialize static function looks like this </p>
  
  <pre><code>class Utils {
    public static function ignoreNullAttributes($object) {
      $ignored_attributes = array();
      foreach($object as $member =&gt; $value) {
        if (is_null($object-&gt;$member)) {
          array_push($ignored_attributes, $member);
        }
       }
       return $ignored_attributes;
     }
  
      public static function serialize($object) {
        $encoder = new XmlEncoder();
        $normalizer = new ObjectNormalizer();
        $normalizer-&gt;setIgnoredAttributes(Utils::ignoreNullAttributes($object));
        $serializer = new Serializer(array($normalizer), array($encoder));
        $str = $serializer-&gt;serialize($object, 'xml')
      }
  }
  </code></pre>
  
  <p>However, this solution does not satisfy me since I have more complicated cases where different <code>Foo</code> can be owned by a same class. e.g. </p>
  
  <pre><code>class Bar
  {
    public $foo1; // (apple=null; pear=2)
    public $foo2; // (apple=2; pear=null)
  
    public function serialize() {
      Utils::serialize($this);
    }
  }
  </code></pre>
  
  <p>Here I cannot use the <code>setIgnoredAttributes</code> method since <code>$foo1</code> and <code>$foo2</code> do not have the same null elements. Furthermore, I do not call the <code>serialize</code> method from the child class (i.e. <code>Foo</code>) here so the <code>setIgnoredAttributes</code> is empty. </p>
  
  <p>Without having to write complex introspection code, how can I hide by default null element with Symfony 2.8 serializer ? I have seen for instance that it is enabled by default with <a href="https://github.com/schmittjoh/JMSSerializerBundle/issues/293" rel="nofollow noreferrer">JMSSerializer</a>.</p>