D
D
dinya172019-11-06 13:09:46
PHP
dinya17, 2019-11-06 13:09:46

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);

JSON example
{
  "uuid": "00004539-73d6-4211-8a32-913bd34f3c8b",
  "phones": [
        {
          "id": 6082892,
          "type": "mob",
          "number": "+79818"
        },
               {
          "id": 60828927,
          "type": "mob",
          "number": "+7988"
        }
      ],
}';

Everything is fine, except that what arrives in phones is not an array with class instances, but an array with json objects.
How to make an array validly deserialized too?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-11-06
@dinya17

$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 question

Ask a Question

731 491 924 answers to any question