How to use Serializer


Serialization and deserialization between an object and different formats (such as JSON or XML) is a very complex topic. Symfony comes with a Serializer component, which provides you with some tools that you can use as needed.

In fact, before you start using it, first familiarize yourself with the serializer, normalizer and encoder, read the article Serializer Component.

Activate Serializer

serializer The service is not available by default. To turn it on, activate it in your configuration file:

PHP:// app/config/config.php$container->loadFromExtension('framework', array(
    // ...
    'serializer' => array(
        'enabled' => true,
    ),));
XML:<!-- app/config/config.xml --><?xml version="1.0" encoding="UTF-8" ?><container xmlns="http://symfony.com/schema/dic/services"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:framework="http://symfony.com/schema/dic/symfony"    xmlns:twig="http://symfony.com/schema/dic/twig"    xsi:schemaLocation="http://symfony.com/schema/dic/services        http://symfony.com/schema/dic/services/services-1.0.xsd        http://symfony.com/schema/dic/symfony        http://symfony.com/schema/dic/symfony/symfony-1.0.xsd        http://symfony.com/schema/dic/twig        http://symfony.com/schema/dic/twig/twig-1.0.xsd">
    <framework:config>
        <!-- ... -->
        <framework:serializer enabled="true" />
    </framework:config></container>
YAML:# app/config/config.ymlframework:    # ...
    serializer:
        enabled: true

Use the Serializer service

Once turned on, serializer The service can be injected into any service when you need it, or used in a controller like this:

// src/AppBundle/Controller/DefaultController.phpnamespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller{
    public function indexAction()
    {
        $serializer = $this->get('serializer');         // ...
    }}

Add Normalizers and Encoders

After being turned on, serializer is available in the container and is loaded with two encoders (JsonEncoder and XmlEncoder) and ObjectNormalizer normalizer.

You can load normalizers and/or encoders by tagging them with serializer.normalizer and serializer.encoder. You can also set the priority of tags to determine the matching order.

The following example demonstrates how to load GetSetMethodNormalizer:

PHP:// app/config/services.phpuse Symfony\Component\DependencyInjection\Definition; $definition = new Definition(
    'Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer'));$definition->setPublic(false);$definition->addTag('serializer.normalizer');$container->setDefinition('get_set_method_normalizer', $definition);
XML:<!-- app/config/services.xml --><services>
    <service id="get_set_method_normalizer" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer" public="false">
        <tag name="serializer.normalizer" />
    </service></services>
YAML:# app/config/services.ymlservices:
    get_set_method_normalizer:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
        public: false
        tags:
            - { name: serializer.normalizer }

Use serialized group Annotations

Enable serialized group annotations through the following configuration:

PHP:// app/config/config.php$container->loadFromExtension('framework', array(
    // ...
    'serializer' => array(
        'enable_annotations' => true,
    ),));
XML:<!-- app/config/config.xml --><framework:config>
    <!-- ... -->
    <framework:serializer enable-annotations="true" /></framework:config>
YAML:# app/config/config.ymlframework:    # ...
    serializer:
        enable_annotations: true

Next, Add @Goups annotations to your class, then when serializing, choose which group to use:

$serializer = $this->get('serializer');$json = $serializer->serialize(
    $someObject,
    'json', array('groups' => array('group1')));

In addition to the @Groups annotation, The serializer component also supports Yaml or Xml files. These components will be automatically loaded when stored in the following location:

  • serialization stored in the Resources/config/ directory under the bundle .yml or serialization.xml;

  • All # stored in the Resources/config/serialization/ directory under the bundle ##*.yml and *.xml.

Enable Metadata caching

Metadata used by the Serializer component, such as groups, can be cached to improve program performance. Any service that implements the

Doctrine\Common\Cache\Cache interface can be used.

A service utilizing

APCu is built into the framework:

PHP:// app/config/config_prod.php$container->loadFromExtension('framework', array(
    // ...
    'serializer' => array(
        'cache' => 'serializer.mapping.cache.apc',
    ),));
XML:<!-- app/config/config_prod.xml --><framework:config>
    <!-- ... -->
    <framework:serializer cache="serializer.mapping.cache.apc" /></framework:config>
YAML:# app/config/config_prod.ymlframework:    # ...
    serializer:
        cache: serializer.mapping.cache.apc

Open a naming converter

2.8 name_converter option was introduced starting with Symfony 2.8.

To use the

name converter service, you can define it using the name_converter option in the configuration file.

The built-in

CamelCase to snake_case name converter (CamelCase to snake converter) can be turned on by setting the serializer.name_converter.camel_case_to_snake_case option value:

PHP:// app/config/config.php$container->loadFromExtension('framework', array(
    // ...
    'serializer' => array(
        'name_converter' => 'serializer.name_converter.camel_case_to_snake_case,
    ),
));
XML:<!-- app/config/config.xml --><framework:config>
    <!-- ... -->
    <framework:serializer name-converter="serializer.name_converter.camel_case_to_snake_case" /></framework:config>

YAML:# app/config/config.ymlframework:    # ...
    serializer:
        name_converter: 'serializer.name_converter.camel_case_to_snake_case'

In-depth Serializer

ApiPlatform provides an API system that supports JSON-LD and Hydra Core Vocabulary hypermedia format. It is built on the Symfony framework and Serializer component. It provides custom normalizers, a custom encoder, custom metadata and a caching system.

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