是否可以在同一个属性上有一个类,有2种类型(1个用于序列化,1个用于反序列化)?
例如,我使用的API允许我将地址作为字符串发送,并且我收到与对象相同的地址。像这样:
请求:
{
"address": "12 rue rivoli, 75001 Paris"
}
响应
{
"address": {
"street": "12 Rue de Rivoli",
"postcode": "75004",
"city": "Paris",
"country": "France"
}
}
答案 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)
所以,这是一个对我有用的解决方案:
定义一种类型,您可以将字段序列化为该类型,即
/ **
在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);
}
}