【发布时间】:2015-06-07 14:55:51
【问题描述】:
我试图遵循这个答案: 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,而不是当我使用侦听器服务时。
提前致谢
【问题讨论】:
-
你能发布你的实际代码吗?
-
我刚刚添加了代码
-
@Mehdi 您是否设法将对象序列化为额外字段(而不是字符串“someValue”)?请看我的另一个问题:stackoverflow.com/questions/45441456/…
标签: php json symfony jms-serializer