In a Symfony 5 project I get this error
Failed to denormalize attribute "options" value for class "App\Entity\Configuration": Expected argument of type "App\Entity\Option", "array" given at property path "options".
when trying to deserialize a JSON-string. The JSON-string looks like
{
"options": [
{
"id": 1,
"name": "x1"
},
{
"id": 2,
"name": "x2"
}
]
}
The configuration Entity is
/**
* @ORM\Entity(repositoryClass=ConfigurationRepository::class)
*/
class Configuration
{
// ...
/**
* @ORM\OneToMany(targetEntity=Option::class, mappedBy="configuration", orphanRemoval=true)
*/
private $options;
// ...
}
and the Option Entity
/**
* @ORM\Entity(repositoryClass=OptionRepository::class)
* @ORM\Table(name="`option`")
*/
class Option
{
// ...
/**
* @ORM\ManyToOne(targetEntity=Configuration::class, inversedBy="options")
* @ORM\JoinColumn(nullable=false)
*/
private $configuration;
// ...
}
The serializer part is
// $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' );
My test JSON-string was originaly created by using the Serializer to serialize an existing Configuration object using the settings stated here for the deserialization. So I guess I am missing some part of the serializer config that tells it how to handle the array -> OneToMany relation (which vice versa it automaticaly encodes)...