How to Use the Serializer

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. // src/Controller/DefaultController.php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Serializer\SerializerInterface;
  5. class DefaultController extends AbstractController
  6. {
  7. public function index(SerializerInterface $serializer)
  8. {
  9. // keep reading for usage examples
  10. }
  11. }

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

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

See the twig reference for more information.

New in version 5.3: A serialize filter was introduced in Symfony 5.3 that uses the Serializer component.

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:

  • JSON: Symfony\Component\Serializer\Encoder\JsonEncoder
  • XML: Symfony\Component\Serializer\Encoder\XmlEncoder
  • CSV: Symfony\Component\Serializer\Encoder\CsvEncoder
  • YAML: Symfony\Component\Serializer\Encoder\YamlEncoder

As well as the following normalizers:

  • Symfony\Component\Serializer\Normalizer\ObjectNormalizer to handle typical data objects
  • Symfony\Component\Serializer\Normalizer\DateTimeNormalizer for objects implementing the DateTimeInterface interface
  • Symfony\Component\Serializer\Normalizer\DateTimeZoneNormalizer for DateTimeZone objects
  • Symfony\Component\Serializer\Normalizer\DateIntervalNormalizer for DateInterval objects
  • Symfony\Component\Serializer\Normalizer\DataUriNormalizer to transform SplFileInfo objects in Data URIs
  • Symfony\Component\Serializer\Normalizer\FormErrorNormalizer for objects implementing the Symfony\Component\Form\FormInterface to normalize form errors.
  • Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer to deal with objects implementing the JsonSerializable interface
  • Symfony\Component\Serializer\Normalizer\ArrayDenormalizer to denormalize arrays of objects using a notation like MyObject[] (note the []` suffix)
  • Symfony\Component\Serializer\Normalizer\ConstraintViolationListNormalizer for objects implementing the Symfony\Component\Validator\ConstraintViolationListInterface interface
  • Symfony\Component\Serializer\Normalizer\ProblemNormalizer for Symfony\Component\ErrorHandler\Exception\FlattenException objects

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.

Here is an example on how to load the Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer, a faster alternative to the ObjectNormalizer when data objects always use getters (getXxx()), issers (isXxx()) or hassers (hasXxx()) to read properties and setters (setXxx()) to change properties:

  • YAML

    1. # config/services.yaml
    2. services:
    3. get_set_method_normalizer:
    4. class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
    5. tags: [serializer.normalizer]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="get_set_method_normalizer" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer">
    9. <tag name="serializer.normalizer"/>
    10. </service>
    11. </services>
    12. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set('get_set_method_normalizer', GetSetMethodNormalizer::class)
    7. ->tag('serializer.normalizer')
    8. ;
    9. };

Using Serialization Groups Annotations

To use annotations, first add support for them via the SensioFrameworkExtraBundle:

  1. $ composer require sensio/framework-extra-bundle

Next, add the @Groups annotations to your class:

  1. // src/Entity/Product.php
  2. namespace App\Entity;
  3. use Doctrine\ORM\Mapping as ORM;
  4. use Symfony\Component\Serializer\Annotation\Groups;
  5. /**
  6. * @ORM\Entity()
  7. */
  8. class Product
  9. {
  10. /**
  11. * @ORM\Id
  12. * @ORM\GeneratedValue
  13. * @ORM\Column(type="integer")
  14. * @Groups({"show_product", "list_product"})
  15. */
  16. private $id;
  17. /**
  18. * @ORM\Column(type="string", length=255)
  19. * @Groups({"show_product", "list_product"})
  20. */
  21. private $name;
  22. /**
  23. * @ORM\Column(type="integer")
  24. * @Groups({"show_product"})
  25. */
  26. private $description;
  27. }

You can now choose which groups to use when serializing:

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

Tip

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

In addition to the @Groups annotation, 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

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

    1. <!-- config/packages/framework.xml -->
    2. <framework:config>
    3. <!-- ... -->
    4. <framework:serializer name-converter="serializer.name_converter.camel_case_to_snake_case"/>
    5. </framework:config>
  • PHP

    1. // config/packages/framework.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->serializer()->nameConverter('serializer.name_converter.camel_case_to_snake_case');
    5. };

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.