Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • 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
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. How to Use the Serializer
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

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

How to Use the Serializer

Edit this page

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

Or you can use the serialize Twig filter in a template:

1
{{ object|serialize(format = 'json') }}

See the twig reference for more information.

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
  • DateTimeNormalizer
  • DateTimeZoneNormalizer
  • DateIntervalNormalizer
  • FormErrorNormalizer
  • DataUriNormalizer
  • JsonSerializableNormalizer
  • ArrayDenormalizer
  • ConstraintViolationListNormalizer
  • ProblemNormalizer
  • BackedEnumNormalizer

Other built-in normalizers and 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.

Serializer Context

The serializer can define a context to control the (de)serialization of resources. This context is passed to all normalizers. For example:

  • DateTimeNormalizer uses datetime_format key as date time format;
  • AbstractObjectNormalizer uses preserve_empty_objects to represent empty objects as {} instead of [] in JSON.
  • Serializer uses empty_array_as_object to represent empty arrays as {} instead of [] in JSON.

You can pass the context as follows:

1
2
3
4
5
6
7
$serializer->serialize($something, 'json', [
    DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);

$serializer->deserialize($someJson, Something::class, 'json', [
    DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);

You can also configure the default context through the framework configuration:

1
2
3
4
5
6
7
# config/packages/framework.yaml
framework:
    # ...
    serializer:
        default_context:
            enable_max_depth: true
            yaml_indentation: 2
1
2
3
4
5
6
7
<!-- config/packages/framework.xml -->
<framework:config>
    <!-- ... -->
    <framework:serializer>
        <default-context enable-max-depth="true" yaml-indentation="2"/>
    </framework:serializer>
</framework:config>
1
2
3
4
5
6
7
8
9
10
11
12
13
// config/packages/framework.php
use Symfony\Component\Serializer\Encoder\YamlEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Config\FrameworkConfig;

return static function (FrameworkConfig $framework) {
    $framework->serializer()
        ->defaultContext([
            AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
            YamlEncoder::YAML_INDENTATION => 2,
        ])
    ;
};

6.2

The option to configure YAML indentation was introduced in Symfony 6.2.

You can also specify the context on a per-property basis:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace App\Model;

use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

class Person
{
    /**
     * @Context({ DateTimeNormalizer::FORMAT_KEY = 'Y-m-d' })
     */
    public $createdAt;

    // ...
}
1
2
3
4
5
6
7
8
9
10
11
12
namespace App\Model;

use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

class Person
{
    #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
    public $createdAt;

    // ...
}
1
2
3
4
5
App\Model\Person:
    attributes:
        createdAt:
            context:
                datetime_format: 'Y-m-d'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
        https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
    <class name="App\Model\Person">
        <attribute name="createdAt">
            <context>
                <entry name="datetime_format">Y-m-d</entry>
            </context>
        </attribute>
    </class>
</serializer>

Use the options to specify context specific to normalization or denormalization:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace App\Model;

use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

class Person
{
    #[Context(
        normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'],
        denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339],
    )]
    public $createdAt;

    // ...
}

You can also restrict the usage of a context to some groups:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace App\Model;

use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

class Person
{
    #[Groups(['extended'])]
    #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])]
    #[Context(
        context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED],
        groups: ['extended'],
    )]
    public $createdAt;

    // ...
}

The attribute/annotation can be repeated as much as needed on a single property. Context without group is always applied first. Then context for the matching groups are merged in the provided order.

Using Context Builders

6.1

Context builders were introduced in Symfony 6.1.

To define the (de)serialization context, you can use "context builders", which are objects that help you to create that context by providing autocompletion, validation, and documentation:

1
2
3
4
use Symfony\Component\Serializer\Context\Normalizer\DateTimeNormalizerContextBuilder;

$contextBuilder = (new DateTimeNormalizerContextBuilder())->withFormat('Y-m-d H:i:s');
$serializer->serialize($something, 'json', $contextBuilder->toArray());

Each normalizer/encoder has its related context builder. To create a more complex (de)serialization context, you can chain them using the withContext() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Serializer\Context\Encoder\CsvEncoderContextBuilder;
use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder;

$initialContext = [
    'custom_key' => 'custom_value',
];

$contextBuilder = (new ObjectNormalizerContextBuilder())
    ->withContext($initialContext)
    ->withGroups(['group1', 'group2']);

$contextBuilder = (new CsvEncoderContextBuilder())
    ->withContext($contextBuilder)
    ->withDelimiter(';');

$serializer->serialize($something, 'csv', $contextBuilder->toArray());

You can also create your context builders to have autocompletion, validation, and documentation for your custom context values.

Using Serialization Groups Attributes

You can add #[Groups] attributes 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
// 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
6
7
use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder;

$context = (new ObjectNormalizerContextBuilder())
    ->withGroups('show_product')
    ->toArray();

$json = $serializer->serialize($product, 'json', $context);

Tip

The value of the groups key can be a single string, or an array of strings.

In addition to the #[Groups] attribute, 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.

Using Nested Attributes

To map nested properties, use the SerializedPath configuration to define their paths using a valid PropertyAccess syntax:

1
2
3
4
5
6
7
8
9
10
11
12
13
namespace App\Model;

use Symfony\Component\Serializer\Annotation\SerializedPath;

class Person
{
    /**
     * @SerializedPath("[profile][information][birthday]")
     */
    private string $birthday;

    // ...
}
1
2
3
4
5
6
7
8
9
10
11
namespace App\Model;

use Symfony\Component\Serializer\Annotation\SerializedPath;

class Person
{
    #[SerializedPath('[profile][information][birthday]')]
    private string $birthday;

    // ...
}
1
2
3
4
App\Model\Person:
    attributes:
        dob:
            serialized_path: '[profile][information][birthday]'
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
        https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
    <class name="App\Model\Person">
        <attribute name="dob" serialized-path="[profile][information][birthday]"/>
    </class>
</serializer>

6.2

The option to configure a SerializedPath was introduced in Symfony 6.2.

Using the configuration from above, denormalizing with a metadata-aware normalizer will write the birthday field from $data onto the Person object:

1
2
3
4
5
6
7
8
9
$data = [
    'profile' => [
        'information' => [
            'birthday' => '01-01-1970',
        ],
    ],
];
$person = $normalizer->denormalize($data, Person::class, 'any');
$person->getBirthday(); // 01-01-1970

When using annotations or attributes, the SerializedPath can either be set on the property or the associated _getter_ method. The SerializedPath cannot be used in combination with a SerializedName for the same property.

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:

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
// config/packages/framework.php
use Symfony\Config\FrameworkConfig;

return static function (FrameworkConfig $framework) {
    $framework->serializer()->nameConverter('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.

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

    Symfony 6.3 is backed by

    Symfony 6.3 is backed by

    Symfony 6.3 is backed by

    Symfony 6.3 is backed by

    Get your Sylius expertise recognized

    Get your Sylius expertise recognized

    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    Symfony footer

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

    Avatar of rkerner, a Symfony contributor

    Thanks rkerner for being a Symfony contributor

    1 commit • 19 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