[英]JMS Serializer expressions not working in virtual property with Symfony 3.4
[英]JMS Serializer: Dynamically change the name of a virtual property at run time
我使用 JMS Serializer Bundle 和 Symfony2。 我正在使用 VirtualProperties。 目前,我使用 SerializedName 注释设置属性的名称。
/**
* @JMS\VirtualProperty()
* @JMS\SerializedName("SOME_NAME")
*/
public function getSomething()
{
return $this->something
}
是否可以在函数内部动态设置序列化名称? 或者是否可以使用 Post/Pre 序列化事件动态影响名称?
谢谢!
我不认为您可以直接执行此操作,但是您可以通过拥有多个虚拟属性来完成类似的操作,每个可能的名称对应一个。 如果名称与特定实体无关,则让该方法返回 null,并在 JMS 配置中禁用 null 序列化。
在你去序列化对象的那一刻,做以下事情:
$this->serializer = SerializerBuilder::create()->setPropertyNamingStrategy(new IdenticalPropertyNamingStrategy())->build();
$json = $this->serializer->serialize($object, 'json');
dump($json);
实体
/**
* @JMS\VirtualProperty("something", exp="context", options={
* @JMS\Expose,
* })
*/
class SomeEntity
{
}
事件监听器
abstract class AbstractEntitySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
[
'event' => Events::POST_SERIALIZE,
'method' => 'onPostSerialize',
'class' => static::getClassName(),
'format' => JsonEncoder::FORMAT,
'priority' => 0,
],
];
}
public function onPostSerialize(ObjectEvent $event): void
{
foreach ($this->getMethodNames() as $methodName) {
$visitor = $event->getVisitor();
$metadata = new VirtualPropertyMetadata(static::getClassName(), $methodName);
if ($visitor->hasData($metadata->name)) {
$value = $this->{$methodName}($event->getObject());
$visitor->visitProperty(
new StaticPropertyMetadata(static::getClassName(), $metadata->name, $value),
$value
);
}
}
}
abstract protected static function getClassName(): string;
abstract protected function getMethodNames(): array;
}
...
class SomeEntitySubscriber extends AbstractEntitySubscriber
{
protected static function getClassName(): string
{
return SomeEntity::class;
}
protected function getMethodNames(): array
{
return ['getSomething'];
}
protected function getSomething(SomeEntity $someEntity)
{
return 'some text';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.