Add extra fields using JMS Serializer bundle Add extra fields using JMS Serializer bundle symfony symfony

Add extra fields using JMS Serializer bundle


I've found the solution by myself,

to add a custom field after the serialization has been done we've to create a listener class like this:

<?phpnamespace Acme\DemoBundle\Listener;use JMS\DiExtraBundle\Annotation\Service;use JMS\DiExtraBundle\Annotation\Tag;use JMS\DiExtraBundle\Annotation\Inject;use JMS\DiExtraBundle\Annotation\InjectParams;use Symfony\Component\HttpKernel\Event\PostResponseEvent;use Acme\DemoBundle\Entity\Team;use JMS\Serializer\Handler\SubscribingHandlerInterface;use JMS\Serializer\EventDispatcher\EventSubscriberInterface;use JMS\Serializer\EventDispatcher\PreSerializeEvent;use JMS\Serializer\EventDispatcher\ObjectEvent;use JMS\Serializer\GraphNavigator;use JMS\Serializer\JsonSerializationVisitor;/** * Add data after serialization * * @Service("acme.listener.serializationlistener") * @Tag("jms_serializer.event_subscriber") */class SerializationListener implements EventSubscriberInterface{    /**     * @inheritdoc     */    static public function getSubscribedEvents()    {        return array(            array('event' => 'serializer.post_serialize', 'class' => 'Acme\DemoBundle\Entity\Team', 'method' => 'onPostSerialize'),        );    }    public function onPostSerialize(ObjectEvent $event)    {        $event->getVisitor()->addData('someKey','someValue');    }}

That way you can add data to the serialized element.

Instead, if you want to edit an object just before serialization use the pre_serialize event, be aware that you need to already have a variable (and the correct serialization groups) if you want to use pre_serialize for adding a value.


I am surprised why nobody have suggested a much more easier way. You need just to use @VirtualProperty:

<?php// .../** * @JMS\VirtualProperty * @JMS\SerializedName("someField") */public function getSomeField(){    return $this->getTitle() . $this->getPromo();}


To further answer the original question. Here is how you limit added data for some serialized groups (in this example some_data is only added when we are not using the list group:

public function onPostSerializeSomeEntityJson(ObjectEvent $event) {    $entity = $event->getObject();    if (!in_array('list', (array)$event->getContext()->attributes->get('groups'))) {        $event->getVisitor()->addData('user_access', array(            'some_data' => 'some_value'        ));    }}

(array)$event->getContext()->attributes->get('groups') contains an array of the used serialized groups.