symfony: [Serializer] ArrayCollection is not denormalised (from json to object)
Symfony version(s) affected: 5.2.7
Description When a model has as a collection described with ArrayCollection<Model>, it’s deserialize into array not ArrayCollection
How to reproduce
<?php
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
require_once './vendor/autoload.php';
class InnerModel
{
/** @var string */
public $id;
}
class Model
{
/** @var ArrayCollection<InnerModel> */
public $items;
}
$serializer = new Serializer([
new ObjectNormalizer(
new ClassMetadataFactory(
new AnnotationLoader()
),
null,
null,
new PhpDocExtractor()
),
new ArrayDenormalizer(),
], ['json' => new JsonEncoder()]);
$data = $serializer->deserialize(
'{"items":[{"id": "1"}]}',
Model::class,
'json',
[
'allow_extra_attributes' => true
]
);
var_dump($data);
Actual result
class Model#32 (1) {
public $items =>
array(1) {
[0] =>
class InnerModel#55 (1) {
public $id =>
string(1) "1"
}
}
}
Expected result
class Model#30 (1) {
public $items =>
class Doctrine\Common\Collections\ArrayCollection#53 (1) {
private $elements =>
array(1) {
[0] =>
class InnerModel#62 (1) {
...
}
}
}
}
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 19 (6 by maintainers)
shame this got closed without a follow up. It would be nice to know how to properly denormalize a Collection as I am currently stuck
Same problem in symfony 6.4
@bizmate @vanomme I just added a setter to an entity which is used by serializer if presented. Here’s an example:
Collection<SourceConfig>|SourceConfig[]actually defines an array of SourceConfig objects as a valid value