如何解决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 举报,一经查实,本站将立刻删除。