当我反序列化我的学说实体时,初始对象是正确构造/启动的,但所有子关系都试图被称为数组。
正在调用根级别对象的addChild(ChildEntity $entity)
方法,但Symfony正在抛出addChild正在接收数组而不是ChildEntity实例的错误。
Symfony自己的序列化程序是否有办法将嵌套数组(子实体)反序列化为实体类型?
JMS Serializer通过在属性上指定@Type("ArrayCollection<ChildEntity>")
注释来处理此问题。
答案 0 :(得分:1)
我相信Symfony序列化程序与JMS Serializer相比会尝试最小化,因此您可能必须为该类实现自己的非规范化程序。您可以看到the section on adding normalizers。
的方式答案 1 :(得分:0)
也许有一种更简单的方法,但是到目前为止,对于Symfony,我正在使用Discriminator接口注释和Object对象数组的type属性。它还可以在一个数组(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;
}
父对象需要将属性定义为接口并获取,添加,删除方法:
/**
* @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]);
}
}