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.
<?php
namespace App\Entity;
use Symfony\Component\Serializer\Attribute\SerializedPath;
class User
{
#[SerializedPath('[profile][info][phone]')]
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 profile.info
structure.
<?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: {"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