0

在 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, null, null, null, null, $defaultContext);
$serializer = new Serializer([$normalizer], [$encoder]);

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

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

4

0 回答 0