Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. How to Use the Serializer
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

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

How to Use the Serializer

Edit this page

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

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

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
2
3
4
5
6
7
8
9
10
11
12
13
// src/Controller/DefaultController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Serializer\SerializerInterface;

class DefaultController extends AbstractController
{
    public function index(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
  • DateTimeZoneNormalizer for DateTimeZone 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)

4.3

The DateTimeZoneNormalizer was introduced in Symfony 4.3.

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.

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:

  • YAML
  • XML
  • PHP
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]
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
        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
// 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 add support for them via the SensioFrameworkExtraBundle:

1
$ composer require sensio/framework-extra-bundle

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

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

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

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
  • CSV

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.

  • Normalizers
  • How to Create your Custom Encoder
  • How to Create your Custom Normalizer
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Take the exam at home

Take the exam at home

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Anand, a Symfony contributor

Thanks Anand (@anandagra) for being a Symfony contributor

1 commit • 2 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?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • 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
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia