Answer the question
In order to leave comments, you need to log in
Symfony serializer how to deserialize an array with objects?
There is a similar question, but it has not yet brought clarity How to implement deserialization of nested object hierarchy using Symfony Serializer?
My question.
There is this cool thing
https://symfony.com/doc/current/components/seriali...
I use it to turn JSON into a valid class instance.
Everything would be fine, but I ran into a problem when I need to assign an array with objects to a class property.
Example
class ContragentDto
{
/**
* @var Phone[]
*/
private $phones = [];
/**
* @return Phone[]
*/
public function getPhones(): array
{
return $this->phones;
}
/**
* @param Phone[] $phones
*/
public function setPhones(array $phones): void
{
$this->phones = $phones;
}
}
$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
$serializer = new Serializer([$normalizer]);
return $serializer->denormalize($array, ContragentDto::class);
{
"uuid": "00004539-73d6-4211-8a32-913bd34f3c8b",
"phones": [
{
"id": 6082892,
"type": "mob",
"number": "+79818"
},
{
"id": 60828927,
"type": "mob",
"number": "+7988"
}
],
}';
Answer the question
In order to leave comments, you need to log in
$reflectionExtractor = new ReflectionExtractor();
$phpDocExtractor = new PhpDocExtractor();
$propertyTypeExtractor = new PropertyInfoExtractor([$reflectionExtractor], [$phpDocExtractor, $reflectionExtractor], [$phpDocExtractor], [$reflectionExtractor], [$reflectionExtractor]);
$normalizer = new ObjectNormalizer(null, null, null, $propertyTypeExtractor);
$arrayNormalizer = new ArrayDenormalizer();
$serializer = new Serializer([$arrayNormalizer, $normalizer]);
return $serializer->denormalize($array, ContragentDto::class);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question