Skip Null Values During Serialization in Symfony 7

Skip Null Values During Serialization in Symfony 7

Serializer component can be used to convert objects to specific format (e.g. JSON, XML) and vice versa. By default, Serializer keeps properties that contain a null value during object serialization.

This tutorial provides example how to skip null values during serialization 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;

    private ?string $phone = null;

    public function getUsername(): string { return $this->username; }
    public function setUsername(string $username): void { $this->username = $username; }

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

Symfony provides the AbstractObjectNormalizer::SKIP_NULL_VALUES option that decides whether to skip null values when serializing an object.

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();
        $user->setUsername('admin');

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

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

Leave a Comment

Cancel reply

Your email address will not be published.