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.



namespace App\Entity;

use Symfony\Component\Serializer\Annotation\SerializedName;

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



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

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