我试图遵循这个答案: Add extra fields using JMS Serializer bundle
但没有变化..
我想在发送之前向序列化实体(在 json 中)添加额外的字段。有什么我错过的吗?
这是我的听众:
<?php
namespace My\MyBundle\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 My\MyBundle\Entity\Dossier;
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("my.listener.serializationlistener")
* @Tag("jms_serializer.event_subscriber")
*/
class SerializationListener implements EventSubscriberInterface
{
/**
* @inheritdoc
*/
static public function getSubscribedEvents()
{
return array(
array('event' => 'serializer.post_serialize', 'class' => 'My\MyBundle\Entity\Dossier', 'method' => 'onPostSerialize'),
);
}
public function onPostSerialize(ObjectEvent $event)
{
$event->getVisitor()->addData('someKey','someValue');
}
}
和我的控制器中的调用:
$serializer = $this->container->get('jms_serializer');
$res = $serializer->serialize($dossier, 'json');
我还添加了以下服务声明:
services:
my.mybundle.listener:
class: My\MyBundle\Listener\SerializationListener
我声明了另一个服务,当我更改它的声明名称时,symfony give and error,而不是当我使用侦听器服务时。
提前致谢