Define Serialized Path for Property in Symfony 7

Define Serialized Path for Property in Symfony 7

The Serializer component facilitates the conversion of objects to a designated format (such as JSON or XML) and the reverse process. In some applications, we may need to use nested structure when serializing a specific property. This tutorial provides example how to define serialized path for property in Symfony 7 application.

Symfony offers the #[SerializedPath] attribute that allows to define serialized path for concrete property.



namespace App\Entity;

use Symfony\Component\Serializer\Attribute\SerializedPath;

class User
    public string $phone;

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

In this scenario, the serialization of the User object involves nesting the phone property within the structure.



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: {"profile":{"info":{"phone":"16111122333"}}}

Please be aware that utilizing both #[SerializedPath] and #[SerializedName] for the same property is not allowed.

Leave a Comment

Cancel reply

Your email address will not be published.