Symfony Serializer 将数组反序列化为 ORM OneToMany 关系

问题描述

在 Symfony 5 项目中,我收到此错误

Failed to denormalize attribute "options" value for class "App\Entity\Configuration": Expected argument of type "App\Entity\Option","array" given at property path "options".

尝试反序列化 JSON 字符串时。 JSON 字符串看起来像

{
  "options": [
    {
      "id": 1,"name": "x1"
    },{
      "id": 2,"name": "x2"
    }
  ]
}

配置实体是

/**
 * @ORM\Entity(repositoryClass=ConfigurationRepository::class)
 */
class Configuration
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity=Option::class,mappedBy="configuration",orphanRemoval=true)
     */
    private $options;
    
    // ...
}

和期权实体

/**
 * @ORM\Entity(repositoryClass=OptionRepository::class)
 * @ORM\Table(name="`option`")
 */
class Option
{
    // ...

    /**
     * @ORM\ManyToOne(targetEntity=Configuration::class,inversedBy="options")
     * @ORM\JoinColumn(nullable=false)
     */
    private $configuration;
    
    // ...
}

序列化部分是

// $configData set to the JSON-string near the top of this post
$encoder = new JsonEncoder();
$defaultContext = [
    AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object,$format,$context) {
        return $object->getName();
    },];
$normalizer = new ObjectNormalizer(null,null,$defaultContext);
$serializer = new Serializer([$normalizer],[$encoder]);

$configurationDeserialized = $serializer->deserialize( $configData,Configuration::class,'json' );

我的测试 JSON 字符串最初是通过使用序列化程序使用此处所述的反序列化设置序列化现有配置对象来创建的。 所以我想我错过了序列化器配置的某些部分,它告诉它如何处理数组 -> OneToMany 关系(反之亦然,它自动编码)...

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...