Define Property Groups for Serialization in Symfony 7

Define Property Groups for Serialization in Symfony 7

Serializer component provided by Symfony is a great way for converting objects to specific format (e.g. JSON, XML) and vice versa. Sometimes, we may need to include only specific object properties during serialization. For this purpose, we can use groups.

This tutorial shows how to define property groups for serialization in Symfony 7 application.

Symfony provides the #[Groups] attribute which allows specifying property groups for serialization.

src/Entity/User.php

<?php

namespace App\Entity;

use Symfony\Component\Serializer\Annotation\Groups;

class User
{
    #[Groups(['contact'])]
    public string $phone;

    #[Groups(['contact', 'address'])]
    private string $country;

    public function getPhone(): string { return $this->phone; }
    public function setPhone(string $phone): void { $this->phone = $phone; }

    public function getCountry(): string { return $this->country; }
    public function setCountry(string $country): void { $this->country = $country; }
}

In our case, only the country property of User object is used for serialization because address group is specified.

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Entity\User;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

class TestController
{
    #[Route('/')]
    public function index(SerializerInterface $serializer): Response
    {
        $user = new User();
        $user->setPhone('16111122333');
        $user->setCountry('United States');

        $json = $serializer->serialize(
            $user,
            JsonEncoder::FORMAT,
            [AbstractNormalizer::GROUPS => 'address']
        );

        return new Response($json); // Output: {"country":"United States"}
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.