Serialize Empty Object as Empty Object in Symfony 7

Serialize Empty Object as Empty Object in Symfony 7

Serializer component enables to convert objects to specific format (e.g. JSON, XML) and vice versa. By default, empty objects are converted to empty array (e.g. [] in JSON) instead of empty object (e.g. {} in JSON).

This tutorial provides example how to serialize empty object as empty object in Symfony 7 application.

Let's say we have the following entity class:

src/Entity/User.php

<?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; }
}

We created an instance of the User class and didn't set any value. By default, it will be converted to [] when JSON format is specified. The Serializer component supports AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS option that allows to convert empty object as empty object. In our case, output will be {} when this option is specified.

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\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

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

        $json = $serializer->serialize(
            $user,
            JsonEncoder::FORMAT,
            [AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true]
        );

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

Leave a Comment

Cancel reply

Your email address will not be published.