Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

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 before using it:

1
$ composer require serializer

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\Controller;
use Symfony\Component\Serializer\SerializerInterface;

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

Adding Normalizers and Encoders

Once enabled, the serializer service will be available in the container and will be loaded with four encoders (JsonEncoder, XmlEncoder, YamlEncoder, and CsvEncoder) and the ObjectNormalizer normalizer.

You can load normalizers and/or encoders 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.

Here is an example on how to load the GetSetMethodNormalizer:

  • YAML
    1
    2
    3
    4
    5
    6
    # config/services.yaml
    services:
        get_set_method_normalizer:
            class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
            public: false
            tags: [serializer.normalizer]
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    <!-- config/services.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"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
    
        <services>
            <service id="get_set_method_normalizer" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer" public="false">
                <tag name="serializer.normalizer" />
            </service>
        </services>
    </container>
    
  • PHP
    1
    2
    3
    4
    5
    6
    7
    // config/services.php
    use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
    
    $container->register('get_set_method_normalizer', GetSetMethodNormalizer::class)
        ->setPublic(false)
        ->addTag('serializer.normalizer')
    ;
    

Using Serialization Groups Annotations

To use annotations, first install the annotations package:

1
$ composer require annotations

Next, add the @Groups annotations to your class and choose which groups to use when serializing:

$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 files are automatically loaded when being stored in one of the following locations:

  • 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 configure the cache, configure the framework.cache.pools key in config/packages/framework.yaml.

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
    2
    3
    4
    5
    # config/packages/framework.yaml
    framework:
        # ...
        serializer:
            name_converter: 'serializer.name_converter.camel_case_to_snake_case'
    
  • XML
    1
    2
    3
    4
    5
    <!-- config/packages/framework.xml -->
    <framework:config>
        <!-- ... -->
        <framework:serializer name-converter="serializer.name_converter.camel_case_to_snake_case" />
    </framework:config>
    
  • PHP
    1
    2
    3
    4
    5
    6
    7
    // config/packages/framework.php
    $container->loadFromExtension('framework', array(
        // ...
        'serializer' => array(
            'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
        ),
    ));
    

Going Further with the Serializer

ApiPlatform provides an API system supporting JSON-LD and Hydra Core Vocabulary hypermedia 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.