Symfony 6 with serializer component - deserialize array of objects

Viewed 30

Install:

  • composer require symfony/property-info
  • composer require symfony/property-access

1 Create own serializer service like

use Symfony\Component\Serializer\Serializer as SymfonySerializer;

class Serializer
{
    private SymfonySerializer $serializer;

    public function __construct()
    {
        $this->serializer = new SymfonySerializer(
            [
                new ArrayDenormalizer(),
                new ObjectNormalizer(null, null, null, new ReflectionExtractor())
            ], ['json' => new JsonEncoder()]
        );
    }

    public function deserialize(string $data, string $type, string $format, array $context = [])
    {
        return $this->serializer->deserialize($data, $type, $format, $context);
    }

}
  1. Create 3 models: Parent,Owner,User

In your model which you put here:

$parent = $this->serializer->deserialize($request->getContent(), Parent::class, 'json');

to get array of objects you need to have property like:


 private array $users = [];

default value is neccessary!

and 3 methods like in this documentation: https://symfony.com/doc/current/components/property_access.html#writing-to-array-properties

addUser, hasUsers and removeUser

Be carefoul....HAS method name must be plural

  1. This own service will work if deserialized JSON has scalar values, objects and also array of objects:
"owner": {
   "firstname": "xxx",
   "lastname": "xxxx"
}
"users":[
{
   "firstname": "xxx",
   "lastname":"yyy"
},
{
   "firstname": "zzzz",
   "lastname":"wwww"
}
]

Pls click arrow up if this answer is useful. Thanks

0 Answers
Related