简体   繁体   English

symfony 序列化程序可以反序列化返回子实体类型的嵌套实体吗?

[英]Can symfony serializer deserialize return nested entity of type child entity?

When I deserialize my doctrine entity, the initial object is constructed/initiated correctly, however all child relations are trying to be called as arrays.当我反序列化我的学说实体时,初始对象被正确构造/启动,但是所有子关系都试图被称为数组。

The root level object's addChild(ChildEntity $entity) method is being called, but Symfony is throwing an error that addChild is receiving an array and not an instance of ChildEntity.正在调用根级对象的addChild(ChildEntity $entity)方法,但是 Symfony 抛出一个错误,表明 addChild 正在接收一个数组而不是 ChildEntity 的实例。

Does Symfony's own serializer have a way to deserialize nested arrays (child entities) to the entity type? Symfony 自己的序列化程序是否可以将嵌套数组(子实体)反序列化为实体类型?

JMS Serializer handles this by specifying a @Type("ArrayCollection<ChildEntity>") annotation on the property. JMS Serializer 通过在属性上指定@Type("ArrayCollection<ChildEntity>")注释来处理此问题。

I believe the Symfony serializer attempts to be minimal compared to the JMS Serializer, so you might have to implement your own denormalizer for the class.我相信 Symfony 序列化器与 JMS 序列化器相比尝试最小化,因此您可能必须为该类实现自己的非规范化器。 You can see how the section on adding normalizers .您可以查看有关添加规范化器的部分如何。

There may be an easier way, but so far with Symfony I am using Discriminator interface annotation and type property for array of Objects.可能有更简单的方法,但到目前为止,我在 Symfony 中使用了 Discriminator 接口注释和对象数组的类型属性。 It can also handle multiple types in one array (MongoDB):它还可以在一个数组 (MongoDB) 中处理多种类型:

namespace App\Model;

use Symfony\Component\Serializer\Annotation\DiscriminatorMap;

/**
 * @DiscriminatorMap(typeProperty="type", mapping={
 *    "text"="App\Model\BlogContentTextModel",
 *    "code"="App\Model\BlogContentCodeModel"
 * })
 */
interface BlogContentInterface
{
    /**
     * @return string
     */
    public function getType(): string;
}

and parent object will need to define property as interface and get, add, remove methods:并且父对象需要将属性定义为接口并获取、添加、删除方法:

    /**
     * @var BlogContentInterface[]
     */
    protected $contents = [];
    
    /**
     * @return BlogContentInterface[]
     */
    public function getContents(): array
    {
        return $this->contents;
    }

    /**
     * @param BlogContentInterface[] $contents
     */
    public function setContents($contents): void
    {
        $this->contents = $contents;
    }

    /**
     * @param BlogContentInterface $content
     */
    public function addContent(BlogContentInterface $content): void
    {
        $this->contents[] = $content;
    }

    /**
     * @param BlogContentInterface $content
     */
    public function removeContent(BlogContentInterface $content): void
    {
        $index = array_search($content, $this->contents);
        if ($index !== false) {
            unset($this->contents[$index]);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM