2 Methods to Set Context to Serializer in Symfony 7

2 Methods to Set Context to Serializer in Symfony 7

The Serializer component facilitates the conversion of objects into a designated format, such as JSON or XML, and also allows the reverse process. The Serializer enables to pass context information during both the serialization and deserialization processes. Context allows controlling and customize the serialization and deserialization processes based on specific conditions or requirements. This tutorial provides 2 methods how to set context to Serializer in Symfony 7.

Method 1 - Direct array usage

We can set context to the Serializer by using PHP arrays directly. For example, to convert empty object as empty object when serializing, we can use the following code:

src/Controller/TestController.php

<?php

namespace App\Controller;

use stdClass;
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
    {
        $obj = new stdClass();
        $json = $serializer->serialize(
            $obj,
            JsonEncoder::FORMAT,
            [AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true]
        );

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

Context modifies Serializer behavior, and the code outputs {} instead of [].

Method 2 - Context builder

Instead of dealing with PHP arrays directly, we can utilize a context builder. It enables the definition of context through a fluent interface, offering autocompletion, validation, and documentation. When context builder is ready, we can invoke the toArray method to pass the context as a plain array to the Serializer.

src/Controller/TestController.php

<?php

namespace App\Controller;

use stdClass;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\SerializerInterface;

class TestController
{
    #[Route('/')]
    public function index(SerializerInterface $serializer): Response
    {
        $builder = (new ObjectNormalizerContextBuilder())
            ->withPreserveEmptyObjects(true);

        $obj = new stdClass();
        $json = $serializer->serialize($obj, JsonEncoder::FORMAT, $builder->toArray());

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

Leave a Comment

Cancel reply

Your email address will not be published.