How to Use the Serializer

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

Installation

In applications using Symfony Flex, run this command toinstall 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 whereyou need it or it can be used in a controller:

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

Adding Normalizers and Encoders

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

Encoders supporting the following formats are enabled:

New in version 4.3: The DateTimeZoneNormalizer was introduced in Symfony 4.3.

Custom normalizers and/or encoders can also be loaded by tagging them asserializer.normalizer andserializer.encoder. It's alsopossible to set the priority of the tag in order to decide the matching order.

Here is an example on how to load theGetSetMethodNormalizer, afaster alternative to the ObjectNormalizer when data objects always usegetters (getXxx()), issers (isXxx()) or hassers (hasXxx()) to readproperties 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. public: false
  6. 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.  
  8. <services>
  9. <service id="get_set_method_normalizer" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer" public="false">
  10. <tag name="serializer.normalizer"/>
  11. </service>
  12. </services>
  13. </container>
  • PHP
  1. // config/services.php
  2. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  3.  
  4. $container->register('get_set_method_normalizer', GetSetMethodNormalizer::class)
  5. ->setPublic(false)
  6. ->addTag('serializer.normalizer')
  7. ;

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 annotationsto your class and choose which groups to use when serializing:

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

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 alsosupports YAML or XML files. These files are automatically loaded when beingstored in one of the following locations:

  • All .yaml and .xml files in the config/serializer/directory.
  • The serialization.yaml or serialization.xml file inthe 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 applicationperformance. By default, the serializer uses the cache.system cache poolwhich is configured using the cache.systemoption.

Enabling a Name Converter

The use of a name converterservice can be defined in the configuration using the name_converteroption.

The built-in CamelCase to snake_case name convertercan be enabled by using the serializer.name_converter.camel_case_to_snake_casevalue:

  • 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. $container->loadFromExtension('framework', [
  3. // ...
  4. 'serializer' => [
  5. 'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
  6. ],
  7. ]);

Going Further with the Serializer

API Platform provides an API system supporting the following formats:

  • JSON-LD along with the Hydra Core Vocabulary
  • OpenAPI v2 (formerly Swagger) and v3
  • GraphQL
  • JSON:API
  • HAL
  • JSON
  • XML
  • YAML
  • CSVIt is built on top of the Symfony Framework and its Serializercomponent. It provides custom normalizers and a custom encoder, custom metadataand a caching system.

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