Define Serialized Name for Property in Symfony 7

Define Serialized Name for Property in Symfony 7

Serializer component can be used for converting objects to specific format (e.g. JSON, XML) and vice versa. In some applications, we may need to use a serialized name that should be different from the property name. This tutorial provides example how to define serialized name for property in Symfony 7 application.

Symfony provides the #[SerializedName] attribute that allows to specify serialized name for specific property.

src/Entity/User.php

<?php

namespace App\Entity;

use Symfony\Component\Serializer\Annotation\SerializedName;

class User
{
    #[SerializedName('phone_number')]
    public string $phone;

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

In our case, phone_number serialized name is used for phone property during User object serialization.

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\SerializerInterface;

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

        $json = $serializer->serialize($user, JsonEncoder::FORMAT);

        return new Response($json); // Output: {"phone_number":"16111122333"}
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.