How to Use the Serializer

Edit this page

How to Use the Serializer

Symfony provides a serializer to serialize/deserialize to and from objects and different formats (e.g. JSON or XML). Before using it, read the Serializer component docs to get familiar with its philosophy and the normalizers and encoders terminology.

Installation

In applications using Symfony Flex, run this command to install the serializer Symfony pack before using it:

1
$ composer require symfony/serializer-pack

Using the Serializer Service

Once enabled, the serializer service can be injected in any service where you need it or it can be used in a controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/Controller/DefaultController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Serializer\SerializerInterface;

class DefaultController extends AbstractController
{
    public function index(SerializerInterface $serializer)
    {
        // keep reading for usage examples
    }
}

Or you can use the serialize Twig filter in a template:

1
{{ object|serialize(format = 'json') }}

See the twig reference for more information.

Adding Normalizers and Encoders

Once enabled, the serializer service will be available in the container. It comes with a set of useful encoders and normalizers.

Encoders supporting the following formats are enabled:

As well as the following normalizers:

Note

The PHP BackedEnum used by BackedEnumNormalizer requires at least PHP 8.1.

Other built-in normalizers and custom normalizers and/or encoders can also be loaded by tagging them as serializer.normalizer and serializer.encoder. It's also possible to set the priority of the tag in order to decide the matching order.

Caution

Always make sure to load the DateTimeNormalizer when serializing the DateTime or DateTimeImmutable classes to avoid excessive memory usage and exposing internal details.

Serializer Context

The serializer can define a context to control the (de)serialization of resources. This context is passed to all normalizers. For example:

  • DateTimeNormalizer uses datetime_format key as date time format;
  • AbstractObjectNormalizer uses preserve_empty_objects to represent empty objects as {} instead of [] in JSON.
  • Serializer uses empty_array_as_object to represent empty arrays as {} instead of [] in JSON.

You can pass the context as follows:

1
2
3
4
5
6
7
$serializer->serialize($something, 'json', [
    DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);

$serializer->deserialize($someJson, Something::class, 'json', [
    DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);

You can also configure the default context through the framework configuration:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
# config/packages/framework.yaml
framework:
    # ...
    serializer:
        default_context:
            enable_max_depth: true

Using Serialization Groups Attributes

You can add #[Groups] attributes to your class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/Entity/Product.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

#[ORM\Entity]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    #[Groups(['show_product', 'list_product'])]
    private $id;

    #[ORM\Column(type: 'string', length: 255)]
    #[Groups(['show_product', 'list_product'])]
    private $name;

    #[ORM\Column(type: 'integer')]
    #[Groups(['show_product'])]
    private $description;
}

You can now choose which groups to use when serializing:

1
2
3
4
5
$json = $serializer->serialize(
    $product,
    'json',
    ['groups' => 'show_product']
);

Tip

The value of the groups key can be a single string, or an array of strings.

In addition to the #[Groups] attribute, the Serializer component also supports YAML or XML files. These files are automatically loaded when being stored in one of the following locations:

  • All *.yaml and *.xml files in the config/serializer/ directory.
  • The serialization.yaml or serialization.xml file in the Resources/config/ directory of a bundle;
  • All *.yaml and *.xml files in the Resources/config/serialization/ directory of a bundle.

Configuring the Metadata Cache

The metadata for the serializer is automatically cached to enhance application performance. By default, the serializer uses the cache.system cache pool which is configured using the cache.system option.

Enabling a Name Converter

The use of a name converter service can be defined in the configuration using the name_converter option.

The built-in CamelCase to snake_case name converter can be enabled by using the serializer.name_converter.camel_case_to_snake_case value:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# config/packages/framework.yaml
framework:
    # ...
    serializer:
        name_converter: 'serializer.name_converter.camel_case_to_snake_case'

Going Further with the Serializer

API Platform provides an API system supporting the following formats:

It is built on top of the Symfony Framework and its Serializer component. It provides custom normalizers and a custom encoder, custom metadata and a caching system.

If you want to leverage the full power of the Symfony Serializer component, take a look at how this bundle works.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
Symfony 6.0 is backed by SensioLabs.