In order to convert objects to specific format (e.g. JSON, XML) and vice versa, we can use Serializer component provided by Symfony. Sometimes we might encounter with API that returns nested responses in which we only need to extract inner values.
This tutorial provides example how to extract only nested values during deserialization in Symfony 7 application.
Let's say we have the following entity class:
<?php
namespace App\Entity;
class User
{
private string $username;
public function getUsername(): string { return $this->username; }
public function setUsername(string $username): void { $this->username = $username; }
}
The Serializer component provides the UnwrappingDenormalizer
class which allows extracting only inner object without creating unnecessary model classes.
<?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\Normalizer\UnwrappingDenormalizer;
use Symfony\Component\Serializer\SerializerInterface;
class TestController
{
#[Route('/')]
public function index(SerializerInterface $serializer): Response
{
$json = '{"data":{"user":{"username":"john"}}}';
$user = $serializer->deserialize(
$json,
User::class,
JsonEncoder::FORMAT,
[UnwrappingDenormalizer::UNWRAP_PATH => '[data][user]']
);
return new Response($user->getUsername()); // Output: john
}
}
Leave a Comment
Cancel reply