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.



namespace App\Entity;

use Symfony\Component\Serializer\Annotation\Groups;

class User
    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.



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
    public function index(SerializerInterface $serializer): Response
        $user = new User();
        $user->setCountry('United States');

        $json = $serializer->serialize(
            [AbstractNormalizer::GROUPS => 'address']

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

Leave a Comment

Cancel reply

Your email address will not be published.