动态JMS序列化程序类型

时间:2017-06-12 13:26:59

标签: symfony jmsserializerbundle jms-serializer

是否可以在同一个属性上有一个类,有2种类型(1个用于序列化,1个用于反序列化)?

例如,我使用的API允许我将地址作为字符串发送,并且我收到与对象相同的地址。像这样:

请求:

{
  "address": "12 rue rivoli, 75001 Paris"
}

响应

{
  "address": {
    "street": "12 Rue de Rivoli",
    "postcode": "75004",
    "city": "Paris",
    "country": "France"
  }
}

2 个答案:

答案 0 :(得分:0)

是的,您可以使用@Accessor Annotation Tag of the JmsSerializer

来实现这一目标
  

可以在要指定的属性上定义此注释   应调用哪个公共方法来检索或设置值   给定的属性:

在您的实体中,这可能如下所示:

# AppBundle/Entity/User
<?php
use JMS\Serializer\Annotation\Accessor;

class User
{


    /** 
     * @var AppBundle\Entity\Address
     * 
     * @Accessor(getter="getAddressAsString",setter="setAddress") 
     */
    private $address;

    // ...
    public function getAddressAsString()
    {
        return sprintf('%s, %s %s', $this->address->getStreet(), $this->address->Postcode(), $this->address->getCity()),
    }

    public function setAddress(Address $address)
    {
        $this->address = $address;
    }
}

答案 1 :(得分:0)

所以,这是一个对我有用的解决方案:

  1. 定义一种类型,您可以将字段序列化为该类型,即

    / **

    • @var字符串
      • @Type(“字符串”) * / 私人$ address;
  2. serializer.pre_deserialize事件(即

    )上实施订阅者/收听者
    class MyPreDeserializationSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
    {
        return [
            [
                'event' => 'serializer.pre_deserialize',
                'method' => 'onPreDeserialize',
                'class' => Video::class,
                'format' => 'json',
            ]
        ];
    }
    
    public function onPreDeserialize(PreDeserializeEvent $event)
    {
        $data = $event->getData();
        $data['address'] = implode(', ', $data['address']);
        $event->setData($data);
    }
    

    }