Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. How to Use the Serializer

How to Use the Serializer

Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

Serializing and deserializing to and from objects and different formats (e.g. JSON or XML) is a very complex topic. Symfony comes with a Serializer Component, which gives you some tools that you can leverage for your solution.

In fact, before you start, get familiar with the serializer, normalizers and encoders by reading the Serializer Component documentation.

Activating the Serializer

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

1
2
3
4
5
6
# app/config/config.yml
framework:
    # ...
    serializer: { enable_annotations: true }
    # Alternatively, if you don't want to use annotations
    #serializer: { enabled: true }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 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"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    <framework:config>
        <!-- ... -->
        <framework:serializer enable-annotations="true"/>
        <!--
        Alternatively, if you don't want to use annotations
        <framework:serializer enabled="true"/>
        -->
    </framework:config>
</container>
1
2
3
4
5
6
7
8
9
// app/config/config.php
$container->loadFromExtension('framework', [
    // ...
    'serializer' => [
        'enable_annotations' => true,
        // Alternatively, if you don't want to use annotations
        //'enabled' => true,
    ],
]);

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/AppBundle/Controller/DefaultController.php
namespace AppBundle\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. It comes with a set of useful encoders and normalizers.

Encoders supporting the following formats are enabled:

  • JSON: JsonEncoder
  • XML: XmlEncoder
  • CSV: CsvEncoder
  • YAML: YamlEncoder

As well as the following normalizers:

  • ObjectNormalizer to handle typical data objects
  • DateTimeNormalizer for objects implementing the DateTimeInterface interface
  • DateIntervalNormalizer for DateInterval objects
  • DataUriNormalizer to transform SplFileInfo objects in Data URIs
  • JsonSerializableNormalizer to deal with objects implementing the JsonSerializable interface
  • ArrayDenormalizer to denormalize arrays of objects using a format like `MyObject[]` (note the `[]` suffix)

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 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:

1
2
3
4
5
6
# app/config/services.yml
services:
    get_set_method_normalizer:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
        public: false
        tags: [serializer.normalizer]
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- app/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
        https://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>
1
2
3
4
5
6
7
// app/config/services.php
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

$container->register('get_set_method_normalizer', GetSetMethodNormalizer::class)
    ->setPublic(false)
    ->addTag('serializer.normalizer')
;

3.4

Support for hasser methods (hasXxx()) in GetSetMethodNormalizer was introduced in Symfony 3.4. In previous Symfony versions only getters (getXxx()) and issers (isXxx()) were supported.

Using Serialization Groups Annotations

Enable serialization groups annotation with the following configuration:

1
2
3
4
5
# app/config/config.yml
framework:
    # ...
    serializer:
        enable_annotations: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 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"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config>
        <!-- ... -->
        <framework:serializer enable-annotations="true"/>
    </framework:config>
</container>
1
2
3
4
5
6
7
// app/config/config.php
$container->loadFromExtension('framework', [
    // ...
    'serializer' => [
        'enable_annotations' => true,
    ],
]);

Next, add the @Groups annotations 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
24
25
26
27
28
29
30
31
// 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']
);

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.yml or serialization.xml file in the Resources/config/ directory of a bundle;
  • All *.yml and *.xml files in the Resources/config/serialization/ directory of a bundle.

Enabling the Metadata Cache

Metadata used by the Serializer component such as groups can be 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:

1
2
3
4
5
# app/config/config.yml
framework:
    # ...
    serializer:
        name_converter: 'serializer.name_converter.camel_case_to_snake_case'
1
2
3
4
5
<!-- app/config/config.xml -->
<framework:config>
    <!-- ... -->
    <framework:serializer name-converter="serializer.name_converter.camel_case_to_snake_case"/>
</framework:config>
1
2
3
4
5
6
7
// app/config/config.php
$container->loadFromExtension('framework', [
    // ...
    'serializer' => [
        '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.

  • How to Create your Custom Encoder
  • How to Create your Custom Normalizer
  • Encoders
  • Normalizers
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    No stress: we've got you covered with our 116 automated quality checks of your code

    No stress: we've got you covered with our 116 automated quality checks of your code

    Version:

    Table of Contents

    • Activating the Serializer
    • Using the Serializer Service
    • Adding Normalizers and Encoders
    • Using Serialization Groups Annotations
    • Enabling the Metadata Cache
    • Enabling a Name Converter
    • Going Further with the Serializer

    Symfony footer

    Avatar of HONORE HOUNWANOU, a Symfony contributor

    Thanks HONORE HOUNWANOU (@mercuryseries) for being a Symfony contributor

    4 commits • 8 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony