Symfony2 JMS Serializer - 修改某些值

时间:2017-07-03 12:24:28

标签: symfony serialization symfony-2.8

我必须使用现有项目,我必须在序列化之前修改一些数据。一个简单的例子:

这是我的序列化程序此刻返回的内容:

[
  {
    "id": 3,
    "reward": "reg"
  }, 
  {
    "id": 4,
    "reward": "inv"
  }, 
]

这就是我想要的回复:

[
  {
    "id": 3,
    "reward": "Registration"
  }, 
  {
    "id": 4,
    "reward": "inviting another user"
  }, 
]

我想重写从数据库到实际可读输出的愚蠢字符串。所以我必须对某些实体的某些字段运行str_replace。我怎样才能做到这一点?

我尝试创建自己的访问者,但似乎只有可能更改“visitString”,这不够具体。还有其他办法吗?

3 个答案:

答案 0 :(得分:1)

您可以为serializer.post_serialize事件创建订阅者,并修改如下数据:

use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;

    class RewardSerializerEventSubscriber implements EventSubscriberInterface
    {
        /**
         * Returns the events to which this class has subscribed.
         *
         * @return array
         */
        public static function getSubscribedEvents()
        {
            return [
                ['event' => 'serializer.post_serialize', 'method' => 'onSerialize', 'class' => YourReward::class],
            ];
        }

        public function onSerialize(ObjectEvent $event)
        {
           /** @var YOURENTITY $object */
           $object  = $event->getObject();
           $visitor = $event->getVisitor();
           if ($visitor->hasData('reward')) {
                $reward = $object->getReward();
                switch ($reward) {
                    case 'reg':
                         $reward = "Registration";
                         break;
                    case 'inv':
                         $reward = 'inviting another user';
                         break;
                    default:
                       break;
                }
               $visitor->setData("reward", $reward);
           }
        }
    }

答案 1 :(得分:0)

你可以使用return DS.Tables[0].AsEnumerable().Select(r => r.Field<int>(0)).ToList(); 事件,你可以替换你的字符串。

阅读本文档: http://jmsyst.com/libs/serializer/master/event_system

答案 2 :(得分:0)

我认为你可以简单地使用Accessor注释来显式设置getter。

http://jmsyst.com/libs/serializer/master/reference/annotations#accessor

/** @JMS\Accessor(getter="getReward") */
private $reward;

public function getReward()
{
    switch ($this->reward) {
            case 'reg':
                return 'Registration';
            case 'inv':
                return 'inviting another user';
            default:
                return $this->reward;
        }
}