Skip to content

The Serializer Component

Edit this page

The Serializer component is meant to be used to turn objects into a specific format (XML, JSON, YAML, ...) and the other way around.

In order to do so, the Serializer component follows the following schema.

When (de)serializing objects, the Serializer uses an array as the intermediary between objects and serialized contents. Encoders will only deal with turning specific formats into arrays and vice versa. The same way, normalizers will deal with turning specific objects into arrays and vice versa. The Serializer deals with calling the normalizers and encoders when serializing objects or deserializing formats.

Serialization is a complex topic. This component may not cover all your use cases out of the box, but it can be useful for developing tools to serialize and deserialize your objects.

Installation

1
$ composer require symfony/serializer

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

To use the ObjectNormalizer, the PropertyAccess component must also be installed.

Usage

See also

This article explains the philosophy of the Serializer and gets you familiar with the concepts of normalizers and encoders. The code examples assume that you use the Serializer as an independent component. If you are using the Serializer in a Symfony application, read How to Use the Serializer after you finish this article.

To use the Serializer component, set up the Serializer specifying which encoders and normalizer are going to be available:

1
2
3
4
5
6
7
8
9
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];

$serializer = new Serializer($normalizers, $encoders);

The preferred normalizer is the ObjectNormalizer, but other normalizers are available. All the examples shown below use the ObjectNormalizer.

Serializing an Object

For the sake of this example, assume the following class already exists in your project:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
namespace App\Model;

class Person
{
    private int $age;
    private string $name;
    private bool $sportsperson;
    private ?\DateTimeInterface $createdAt;

    // Getters
    public function getAge(): int
    {
        return $this->age;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    // Issers
    public function isSportsperson(): bool
    {
        return $this->sportsperson;
    }

    // Setters
    public function setAge(int $age): void
    {
        $this->age = $age;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    public function setSportsperson(bool $sportsperson): void
    {
        $this->sportsperson = $sportsperson;
    }

    public function setCreatedAt(?\DateTimeInterface $createdAt = null): void
    {
        $this->createdAt = $createdAt;
    }
}

Now, if you want to serialize this object into JSON, you only need to use the Serializer service created before:

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

$person = new Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsperson(false);

$jsonContent = $serializer->serialize($person, 'json');

// $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}

echo $jsonContent; // or return it in a Response

The first parameter of the serialize() is the object to be serialized and the second is used to choose the proper encoder, in this case JsonEncoder.

Deserializing an Object

You'll now learn how to do the exact opposite. This time, the information of the Person class would be encoded in XML format:

1
2
3
4
5
6
7
8
9
10
11
use App\Model\Person;

$data = <<<EOF
<person>
    <name>foo</name>
    <age>99</age>
    <sportsperson>false</sportsperson>
</person>
EOF;

$person = $serializer->deserialize($data, Person::class, 'xml');

In this case, deserialize() needs three parameters:

  1. The information to be decoded
  2. The name of the class this information will be decoded to
  3. The encoder used to convert that information into an array

By default, additional attributes that are not mapped to the denormalized object will be ignored by the Serializer component. If you prefer to throw an exception when this happens, set the AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES context option to false and provide an object that implements ClassMetadataFactoryInterface when constructing the normalizer:

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

$data = <<<EOF
<person>
    <name>foo</name>
    <age>99</age>
    <city>Paris</city>
</person>
EOF;

// $loader is any of the valid loaders explained later in this article
$classMetadataFactory = new ClassMetadataFactory($loader);
$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([$normalizer]);

// this will throw a Symfony\Component\Serializer\Exception\ExtraAttributesException
// because "city" is not an attribute of the Person class
$person = $serializer->deserialize($data, Person::class, 'xml', [
    AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false,
]);

Deserializing in an Existing Object

The serializer can also be used to update an existing object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ...
$person = new Person();
$person->setName('bar');
$person->setAge(99);
$person->setSportsperson(true);

$data = <<<EOF
<person>
    <name>foo</name>
    <age>69</age>
</person>
EOF;

$serializer->deserialize($data, Person::class, 'xml', [AbstractNormalizer::OBJECT_TO_POPULATE => $person]);
// $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true)

This is a common need when working with an ORM.

The AbstractNormalizer::OBJECT_TO_POPULATE is only used for the top level object. If that object is the root of a tree structure, all child elements that exist in the normalized data will be re-created with new instances.

When the AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE option is set to true, existing children of the root OBJECT_TO_POPULATE are updated from the normalized data, instead of the denormalizer re-creating them. Note that DEEP_OBJECT_TO_POPULATE only works for single child objects, but not for arrays of objects. Those will still be replaced when present in the normalized data.

Context

Many Serializer features can be configured using a context.

Attributes Groups

Sometimes, you want to serialize different sets of attributes from your entities. Groups are a handy way to achieve this need.

Assume you have the following plain-old-PHP object:

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

class MyObj
{
    public string $foo;

    private string $bar;

    public function getBar(): string
    {
        return $this->bar;
    }

    public function setBar($bar): string
    {
        return $this->bar = $bar;
    }
}

The definition of serialization can be specified using annotations, attributes, XML or YAML. The ClassMetadataFactory that will be used by the normalizer must be aware of the format to use.

The following code shows how to initialize the ClassMetadataFactory for each format:

  • Annotations in PHP files:

    1
    2
    3
    4
    5
    use Doctrine\Common\Annotations\AnnotationReader;
    use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
    use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
    
    $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
  • Attributes in PHP files:

    1
    2
    3
    4
    use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
    use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
    
    $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());
  • YAML files:

    1
    2
    3
    4
    use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
    use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
    
    $classMetadataFactory = new ClassMetadataFactory(new YamlFileLoader('/path/to/your/definition.yaml'));
  • XML files:

    1
    2
    3
    4
    use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
    use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader;
    
    $classMetadataFactory = new ClassMetadataFactory(new XmlFileLoader('/path/to/your/definition.xml'));

6.4

The AttributeLoader was introduced in Symfony 6.4. Prior to this, the AnnotationLoader must be used.

6.4

Reading annotations in PHP files is deprecated since Symfony 6.4. Also, the AnnotationLoader was deprecated in Symfony 6.4.

Then, create your groups definition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace Acme;

use Symfony\Component\Serializer\Annotation\Groups;

class MyObj
{
    #[Groups(['group1', 'group2'])]
    public string $foo;

    #[Groups(['group4'])]
    public string $anotherProperty;

    #[Groups(['group3'])]
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

You are now able to serialize only attributes in the groups you want:

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
use Acme\MyObj;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$obj = new MyObj();
$obj->foo = 'foo';
$obj->anotherProperty = 'anotherProperty';
$obj->setBar('bar');

$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([$normalizer]);

$data = $serializer->normalize($obj, null, ['groups' => 'group1']);
// $data = ['foo' => 'foo'];

$obj2 = $serializer->denormalize(
    ['foo' => 'foo', 'anotherProperty' => 'anotherProperty', 'bar' => 'bar'],
    MyObj::class,
    null,
    ['groups' => ['group1', 'group3']]
);
// $obj2 = MyObj(foo: 'foo', bar: 'bar')

// To get all groups, use the special value `*` in `groups`
$obj3 = $serializer->denormalize(
    ['foo' => 'foo', 'anotherProperty' => 'anotherProperty', 'bar' => 'bar'],
    MyObj::class,
    null,
    ['groups' => ['*']]
);
// $obj2 = MyObj(foo: 'foo', anotherProperty: 'anotherProperty', bar: 'bar')

Selecting Specific Attributes

It is also possible to serialize only a set of specific attributes:

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
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class User
{
    public string $familyName;
    public string $givenName;
    public Company $company;
}

class Company
{
    public string $name;
    public string $address;
}

$company = new Company();
$company->name = 'Les-Tilleuls.coop';
$company->address = 'Lille, France';

$user = new User();
$user->familyName = 'Dunglas';
$user->givenName = 'Kévin';
$user->company = $company;

$serializer = new Serializer([new ObjectNormalizer()]);

$data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
// $data = ['familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']];

Only attributes that are not ignored (see below) are available. If some serialization groups are set, only attributes allowed by those groups can be used.

As for groups, attributes can be selected during both the serialization and deserialization processes.

Ignoring Attributes

All accessible attributes are included by default when serializing objects. There are two options to ignore some of those attributes.

Option 1: Using #[Ignore] Attribute

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

use Symfony\Component\Serializer\Annotation\Ignore;

class MyClass
{
    public string $foo;

    #[Ignore]
    public string $bar;
}

You can now ignore specific attributes during serialization:

1
2
3
4
5
6
7
8
9
10
11
12
13
use App\Model\MyClass;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$obj = new MyClass();
$obj->foo = 'foo';
$obj->bar = 'bar';

$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([$normalizer]);

$data = $serializer->normalize($obj);
// $data = ['foo' => 'foo'];

Option 2: Using the Context

Pass an array with the names of the attributes to ignore using the AbstractNormalizer::IGNORED_ATTRIBUTES key in the context of the serializer method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Acme\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$person = new Person();
$person->setName('foo');
$person->setAge(99);

$normalizer = new ObjectNormalizer();
$encoder = new JsonEncoder();

$serializer = new Serializer([$normalizer], [$encoder]);
$serializer->serialize($person, 'json', [AbstractNormalizer::IGNORED_ATTRIBUTES => ['age']]); // Output: {"name":"foo"}

Converting Property Names when Serializing and Deserializing

Sometimes serialized attributes must be named differently than properties or getter/setter methods of PHP classes.

The Serializer component provides a handy way to translate or map PHP field names to serialized names: The Name Converter System.

Given you have the following object:

1
2
3
4
5
class Company
{
    public string $name;
    public string $address;
}

And in the serialized form, all attributes must be prefixed by org_ like the following:

1
{"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}

A custom name converter can handle such cases:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class OrgPrefixNameConverter implements NameConverterInterface
{
    public function normalize(string $propertyName): string
    {
        return 'org_'.$propertyName;
    }

    public function denormalize(string $propertyName): string
    {
        // removes 'org_' prefix
        return str_starts_with($propertyName, 'org_') ? substr($propertyName, 4) : $propertyName;
    }
}

The custom name converter can be used by passing it as second parameter of any class extending AbstractNormalizer, including GetSetMethodNormalizer and PropertyNormalizer:

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

$nameConverter = new OrgPrefixNameConverter();
$normalizer = new ObjectNormalizer(null, $nameConverter);

$serializer = new Serializer([$normalizer], [new JsonEncoder()]);

$company = new Company();
$company->name = 'Acme Inc.';
$company->address = '123 Main Street, Big City';

$json = $serializer->serialize($company, 'json');
// {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}
$companyCopy = $serializer->deserialize($json, Company::class, 'json');
// Same data as $company

Note

You can also implement AdvancedNameConverterInterface to access the current class name, format and context.

CamelCase to snake_case

In many formats, it's common to use underscores to separate words (also known as snake_case). However, in Symfony applications is common to use CamelCase to name properties (even though the PSR-1 standard doesn't recommend any specific case for property names).

Symfony provides a built-in name converter designed to transform between snake_case and CamelCased styles during serialization and deserialization processes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

$normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter());

class Person
{
    public function __construct(
        private string $firstName,
    ) {
    }

    public function getFirstName(): string
    {
        return $this->firstName;
    }
}

$kevin = new Person('Kévin');
$normalizer->normalize($kevin);
// ['first_name' => 'Kévin'];

$anne = $normalizer->denormalize(['first_name' => 'Anne'], 'Person');
// Person object with firstName: 'Anne'

Configure name conversion using metadata

When using this component inside a Symfony application and the class metadata factory is enabled as explained in the Attributes Groups section, this is already set up and you only need to provide the configuration. Otherwise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ...
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());

$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);

$serializer = new Serializer(
    [new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
    ['json' => new JsonEncoder()]
);

Now configure your name conversion mapping. Consider an application that defines a Person entity with a firstName property:

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

use Symfony\Component\Serializer\Annotation\SerializedName;

class Person
{
    public function __construct(
        #[SerializedName('customer_name')]
        private string $firstName,
    ) {
    }

    // ...
}

This custom mapping is used to convert property names when serializing and deserializing objects:

1
2
$serialized = $serializer->serialize(new Person('Kévin'), 'json');
// {"customer_name": "Kévin"}

Serializing Boolean Attributes

If you are using isser methods (methods prefixed by is, like App\Model\Person::isSportsperson()), the Serializer component will automatically detect and use it to serialize related attributes.

The ObjectNormalizer also takes care of methods starting with has, get, and can.

6.1

The support of canners (methods prefixed by can) was introduced in Symfony 6.1.

Using Callbacks to Serialize Properties with Object Instances

When serializing, you can set a callback to format a specific object property:

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
use App\Model\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;

$encoder = new JsonEncoder();

// all callback parameters are optional (you can omit the ones you don't use)
$dateCallback = function (object $attributeValue, object $object, string $attributeName, ?string $format = null, array $context = []): string {
    return $attributeValue instanceof \DateTime ? $attributeValue->format(\DateTime::ATOM) : '';
};

$defaultContext = [
    AbstractNormalizer::CALLBACKS => [
        'createdAt' => $dateCallback,
    ],
];

$normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);

$serializer = new Serializer([$normalizer], [$encoder]);

$person = new Person();
$person->setName('cordoval');
$person->setAge(34);
$person->setCreatedAt(new \DateTime('now'));

$serializer->serialize($person, 'json');
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}

Normalizers

Normalizers turn objects into arrays and vice versa. They implement NormalizerInterface for normalizing (object to array) and DenormalizerInterface for denormalizing (array to object).

Normalizers are enabled in the serializer passing them as its first argument:

1
2
3
4
5
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, []);

Built-in Normalizers

The Serializer component provides several built-in normalizers:

ObjectNormalizer

This normalizer leverages the PropertyAccess Component to read and write in the object. It means that it can access to properties directly and through getters, setters, hassers, issers, canners, adders and removers. It supports calling the constructor during the denormalization process.

Objects are normalized to a map of property names and values (names are generated by removing the get, set, has, is, can, add or remove prefix from the method name and transforming the first letter to lowercase; e.g. getFirstName() -> firstName).

The ObjectNormalizer is the most powerful normalizer. It is configured by default in Symfony applications with the Serializer component enabled.

GetSetMethodNormalizer

This normalizer reads the content of the class by calling the "getters" (public methods starting with "get"). It will denormalize data by calling the constructor and the "setters" (public methods starting with "set").

Objects are normalized to a map of property names and values (names are generated by removing the get prefix from the method name and transforming the first letter to lowercase; e.g. getFirstName() -> firstName).

PropertyNormalizer

This normalizer directly reads and writes public properties as well as private and protected properties (from both the class and all of its parent classes) by using PHP reflection. It supports calling the constructor during the denormalization process.

Objects are normalized to a map of property names to property values.

If you prefer to only normalize certain properties (e.g. only public properties) set the PropertyNormalizer::NORMALIZE_VISIBILITY context option and combine the following values: PropertyNormalizer::NORMALIZE_PUBLIC, PropertyNormalizer::NORMALIZE_PROTECTED or PropertyNormalizer::NORMALIZE_PRIVATE.

6.2

The PropertyNormalizer::NORMALIZE_VISIBILITY context option and its values were introduced in Symfony 6.2.

JsonSerializableNormalizer

This normalizer works with classes that implement JsonSerializable.

It will call the JsonSerializable::jsonSerialize() method and then further normalize the result. This means that nested JsonSerializable classes will also be normalized.

This normalizer is particularly helpful when you want to gradually migrate from an existing codebase using simple json_encode to the Symfony Serializer by allowing you to mix which normalizers are used for which classes.

Unlike with json_encode circular references can be handled.

DateTimeNormalizer
This normalizer converts DateTimeInterface objects (e.g. DateTime and DateTimeImmutable) into strings. By default, it uses the RFC3339 format.
DateTimeZoneNormalizer
This normalizer converts DateTimeZone objects into strings that represent the name of the timezone according to the list of PHP timezones.
DataUriNormalizer
This normalizer converts SplFileInfo objects into a data URI string (data:...) such that files can be embedded into serialized data.
DateIntervalNormalizer
This normalizer converts DateInterval objects into strings. By default, it uses the P%yY%mM%dDT%hH%iM%sS format.
BackedEnumNormalizer

This normalizer converts a BackedEnum objects into strings or integers.

By default, an exception is thrown when data is not a valid backed enumeration. If you want null instead, you can set the BackedEnumNormalizer::ALLOW_INVALID_VALUES option.

6.3

The BackedEnumNormalizer::ALLOW_INVALID_VALUES context option was introduced in Symfony 6.3.

FormErrorNormalizer

This normalizer works with classes that implement FormInterface.

It will get errors from the form and normalize them into a normalized array.

ConstraintViolationListNormalizer
This normalizer converts objects that implement ConstraintViolationListInterface into a list of errors according to the RFC 7807 standard.
ProblemNormalizer
Normalizes errors according to the API Problem spec RFC 7807.
CustomNormalizer
Normalizes a PHP object using an object that implements NormalizableInterface.
UidNormalizer

This normalizer converts objects that extend AbstractUid into strings. The default normalization format for objects that implement Uuid is the RFC 4122 format (example: d9e7a184-5d5b-11ea-a62a-3499710062d0). The default normalization format for objects that implement Ulid is the Base 32 format (example: 01E439TP9XJZ9RPFH3T1PYBCR8). You can change the string format by setting the serializer context option UidNormalizer::NORMALIZATION_FORMAT_KEY to UidNormalizer::NORMALIZATION_FORMAT_BASE_58, UidNormalizer::NORMALIZATION_FORMAT_BASE_32 or UidNormalizer::NORMALIZATION_FORMAT_RFC_4122.

Also it can denormalize uuid or ulid strings to Uuid or Ulid. The format does not matter.

TranslatableNormalizer

This normalizer converts objects that implement TranslatableInterface into translated strings, using the trans() method. You can define the locale to use to translate the object by setting the TranslatableNormalizer::NORMALIZATION_LOCALE_KEY serializer context option.

6.4

The TranslatableNormalizer was introduced in Symfony 6.4.

Note

You can also create your own Normalizer to use another structure. Read more at How to Create your Custom Normalizer.

Certain normalizers are enabled by default when using the Serializer component in a Symfony application, additional ones can be enabled by tagging them with serializer.normalizer.

Here is an example of how to enable the built-in GetSetMethodNormalizer, a faster alternative to the ObjectNormalizer:

1
2
3
4
5
6
7
# config/services.yaml
services:
    # ...

    get_set_method_normalizer:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
        tags: [serializer.normalizer]

Encoders

Encoders turn arrays into formats and vice versa. They implement EncoderInterface for encoding (array to format) and DecoderInterface for decoding (format to array).

You can add new encoders to a Serializer instance by using its second constructor argument:

1
2
3
4
5
6
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;

$encoders = [new XmlEncoder(), new JsonEncoder()];
$serializer = new Serializer([], $encoders);

Built-in Encoders

The Serializer component provides several built-in encoders:

JsonEncoder
This class encodes and decodes data in JSON.
XmlEncoder
This class encodes and decodes data in XML.
YamlEncoder
This encoder encodes and decodes data in YAML. This encoder requires the Yaml Component.
CsvEncoder
This encoder encodes and decodes data in CSV.

Note

You can also create your own Encoder to use another structure. Read more at How to Create your Custom Encoder.

All these encoders are enabled by default when using the Serializer component in a Symfony application.

The JsonEncoder

The JsonEncoder encodes to and decodes from JSON strings, based on the PHP json_encode and json_decode functions. It can be useful to modify how these functions operate in certain instances by providing options such as JSON_PRESERVE_ZERO_FRACTION. You can use the serialization context to pass in these options using the key json_encode_options or json_decode_options respectively:

1
$this->serializer->serialize($data, 'json', ['json_encode_options' => \JSON_PRESERVE_ZERO_FRACTION]);

These are the options available:

Option Description Default
json_decode_associative If set to true returns the result as an array, returns a nested stdClass hierarchy otherwise. false
json_decode_detailed_errors If set to true, exceptions thrown on parsing of JSON are more specific. Requires seld/jsonlint package. false
json_decode_options $flags passed to json_decode function. 0
json_encode_options $flags passed to json_encode function. \JSON_PRESERVE_ZERO_FRACTION
json_decode_recursion_depth Sets maximum recursion depth. 512

6.4

The support of json_decode_detailed_errors was introduced in Symfony 6.4.

The CsvEncoder

The CsvEncoder encodes to and decodes from CSV.

The CsvEncoder Context Options

The encode() method defines a third optional parameter called context which defines the configuration options for the CsvEncoder an associative array:

1
$csvEncoder->encode($array, 'csv', $context);

These are the options available:

Option Description Default
csv_delimiter Sets the field delimiter separating values (one character only) ,
csv_enclosure Sets the field enclosure (one character only) "
csv_end_of_line Sets the character(s) used to mark the end of each line in the CSV file \n
csv_escape_char Sets the escape character (at most one character) empty string
csv_key_separator Sets the separator for array's keys during its flattening .
csv_headers Sets the order of the header and data columns E.g.: if $data = ['c' => 3, 'a' => 1, 'b' => 2] and $options = ['csv_headers' => ['a', 'b', 'c']] then serialize($data, 'csv', $options) returns a,b,c\n1,2,3 [], inferred from input data's keys
csv_escape_formulas Escapes fields containing formulas by prepending them with a \t character false
as_collection Always returns results as a collection, even if only one line is decoded. true
no_headers Setting to false will use first row as headers. true generate numeric headers. false
output_utf8_bom Outputs special UTF-8 BOM along with encoded data false

The XmlEncoder

This encoder transforms arrays into XML and vice versa.

For example, take an object normalized as following:

1
['foo' => [1, 2], 'bar' => true];

The XmlEncoder will encode this object like that:

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8" ?>
<response>
    <foo>1</foo>
    <foo>2</foo>
    <bar>1</bar>
</response>

The special # key can be used to define the data of a node:

1
2
3
4
5
6
7
8
9
['foo' => ['@bar' => 'value', '#' => 'baz']];

// is encoded as follows:
// <?xml version="1.0"?>
// <response>
//     <foo bar="value">
//        baz
//     </foo>
// </response>

Furthermore, keys beginning with @ will be considered attributes, and the key #comment can be used for encoding XML comments:

1
2
3
4
5
6
7
8
9
10
11
$encoder = new XmlEncoder();
$encoder->encode([
    'foo' => ['@bar' => 'value'],
    'qux' => ['#comment' => 'A comment'],
], 'xml');
// will return:
// <?xml version="1.0"?>
// <response>
//     <foo bar="value"/>
//     <qux><!-- A comment --!><qux>
// </response>

You can pass the context key as_collection in order to have the results always as a collection.

Note

You may need to add some attributes on the root node:

1
2
3
4
5
6
7
8
9
10
11
12
$encoder = new XmlEncoder();
$encoder->encode([
    '@attribute1' => 'foo',
    '@attribute2' => 'bar',
    '#' => ['foo' => ['@bar' => 'value', '#' => 'baz']]
], 'xml');

// will return:
// <?xml version="1.0"?>
// <response attribute1="foo" attribute2="bar">
// <foo bar="value">baz</foo>
// </response>

Tip

XML comments are ignored by default when decoding contents, but this behavior can be changed with the optional context key XmlEncoder::DECODER_IGNORED_NODE_TYPES.

Data with #comment keys are encoded to XML comments by default. This can be changed by adding the \XML_COMMENT_NODE option to the XmlEncoder::ENCODER_IGNORED_NODE_TYPES key of the $defaultContext of the XmlEncoder constructor or directly to the $context argument of the encode() method:

1
$xmlEncoder->encode($array, 'xml', [XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [\XML_COMMENT_NODE]]);

The XmlEncoder Context Options

The encode() method defines a third optional parameter called context which defines the configuration options for the XmlEncoder an associative array:

1
$xmlEncoder->encode($array, 'xml', $context);

These are the options available:

Option Description Default
xml_format_output If set to true, formats the generated XML with line breaks and indentation false
xml_version Sets the XML version attribute 1.0
xml_encoding Sets the XML encoding attribute utf-8
xml_standalone Adds standalone attribute in the generated XML true
xml_type_cast_attributes This provides the ability to forget the attribute type casting true
xml_root_node_name Sets the root node name response
as_collection Always returns results as a collection, even if only one line is decoded false
decoder_ignored_node_types Array of node types (DOM XML_* constants) to be ignored while decoding [\XML_PI_NODE, \XML_COMMENT_NODE]
encoder_ignored_node_types Array of node types (DOM XML_* constants) to be ignored while encoding []
load_options XML loading options with libxml \LIBXML_NONET | \LIBXML_NOBLANKS
save_options XML saving options with libxml 0
remove_empty_tags If set to true, removes all empty tags in the generated XML false
cdata_wrapping If set to false, will not wrap any value containing one of the following characters ( <, >, &) in a CDATA section like following: <![CDATA[...]]> true

6.4

The `cdata_wrapping` option was introduced in Symfony 6.4.

Example with custom context:

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
use Symfony\Component\Serializer\Encoder\XmlEncoder;

// create encoder with specified options as new default settings
$xmlEncoder = new XmlEncoder(['xml_format_output' => true]);

$data = [
    'id' => 'IDHNQIItNyQ',
    'date' => '2019-10-24',
];

// encode with default context
$xmlEncoder->encode($data, 'xml');
// outputs:
// <?xml version="1.0"?>
// <response>
//   <id>IDHNQIItNyQ</id>
//   <date>2019-10-24</date>
// </response>

// encode with modified context
$xmlEncoder->encode($data, 'xml', [
    'xml_root_node_name' => 'track',
    'encoder_ignored_node_types' => [
        \XML_PI_NODE, // removes XML declaration (the leading xml tag)
    ],
]);
// outputs:
// <track>
//   <id>IDHNQIItNyQ</id>
//   <date>2019-10-24</date>
// </track>

The YamlEncoder

This encoder requires the Yaml Component and transforms from and to Yaml.

The YamlEncoder Context Options

The encode() method, like other encoder, uses context to set configuration options for the YamlEncoder an associative array:

1
$yamlEncoder->encode($array, 'yaml', $context);

These are the options available:

Option Description Default
yaml_inline The level where you switch to inline YAML 0
yaml_indent The level of indentation (used internally) 0
yaml_flags A bit field of Yaml::DUMP_* / PARSE_* constants to customize the encoding / decoding YAML string 0

Context Builders

Instead of passing plain PHP arrays to the serialization context, you can use "context builders" to define the context using a fluent interface:

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());

6.1

Context builders were introduced in Symfony 6.1.

Note

The Serializer component provides a context builder for each normalizer and encoder.

You can also create custom context builders to deal with your context values.

Skipping null Values

By default, the Serializer will preserve properties containing a null value. You can change this behavior by setting the AbstractObjectNormalizer::SKIP_NULL_VALUES context option to true:

1
2
3
4
5
6
7
8
$dummy = new class {
    public ?string $foo = null;
    public string $bar = 'notNull';
};

$normalizer = new ObjectNormalizer();
$result = $normalizer->normalize($dummy, 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]);
// ['bar' => 'notNull']

Require all Properties

By default, the Serializer will add null to nullable properties when the parameters for those are not provided. You can change this behavior by setting the AbstractNormalizer::REQUIRE_ALL_PROPERTIES context option to true:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Dummy
{
    public function __construct(
        public string $foo,
        public ?string $bar,
    ) {
    }
}

$data = ['foo' => 'notNull'];

$normalizer = new ObjectNormalizer();
$result = $normalizer->denormalize($data, Dummy::class, 'json', [AbstractNormalizer::REQUIRE_ALL_PROPERTIES => true]);
// throws Symfony\Component\Serializer\Exception\MissingConstructorArgumentException

6.3

The AbstractNormalizer::PREVENT_NULLABLE_FALLBACK context option was introduced in Symfony 6.3.

Skipping Uninitialized Properties

In PHP, typed properties have an uninitialized state which is different from the default null of untyped properties. When you try to access a typed property before giving it an explicit value, you get an error.

To avoid the Serializer throwing an error when serializing or normalizing an object with uninitialized properties, by default the object normalizer catches these errors and ignores such properties.

You can disable this behavior by setting the AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES context option to false:

1
2
3
4
5
6
7
8
class Dummy {
    public string $foo = 'initialized';
    public string $bar; // uninitialized
}

$normalizer = new ObjectNormalizer();
$result = $normalizer->normalize(new Dummy(), 'json', [AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES => false]);
// throws Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException as normalizer cannot read uninitialized properties

Note

Calling PropertyNormalizer::normalize or GetSetMethodNormalizer::normalize with AbstractObjectNormalizer::SKIP_UNINITIALIZED_VALUES context option set to false will throw an \Error instance if the given object has uninitialized properties as the normalizer cannot read them (directly or via getter/isser methods).

Collecting Type Errors While Denormalizing

When denormalizing a payload to an object with typed properties, you'll get an exception if the payload contains properties that don't have the same type as the object.

In those situations, use the COLLECT_DENORMALIZATION_ERRORS option to collect all exceptions at once, and to get the object partially denormalized:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
    $dto = $serializer->deserialize($request->getContent(), MyDto::class, 'json', [
        DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true,
    ]);
} catch (PartialDenormalizationException $e) {
    $violations = new ConstraintViolationList();
    /** @var NotNormalizableValueException $exception */
    foreach ($e->getErrors() as $exception) {
        $message = sprintf('The type must be one of "%s" ("%s" given).', implode(', ', $exception->getExpectedTypes()), $exception->getCurrentType());
        $parameters = [];
        if ($exception->canUseMessageForUser()) {
            $parameters['hint'] = $exception->getMessage();
        }
        $violations->add(new ConstraintViolation($message, '', $parameters, null, $exception->getPath(), null));
    }

    return $this->json($violations, 400);
}

Handling Circular References

Circular references are common when dealing with entity relations:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Organization
{
    private string $name;
    private array $members;

    public function setName($name): void
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function setMembers(array $members): void
    {
        $this->members = $members;
    }

    public function getMembers(): array
    {
        return $this->members;
    }
}

class Member
{
    private string $name;
    private Organization $organization;

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function setOrganization(Organization $organization): void
    {
        $this->organization = $organization;
    }

    public function getOrganization(): Organization
    {
        return $this->organization;
    }
}

To avoid infinite loops, GetSetMethodNormalizer or ObjectNormalizer throw a CircularReferenceException when such a case is encountered:

1
2
3
4
5
6
7
8
9
10
$member = new Member();
$member->setName('Kévin');

$organization = new Organization();
$organization->setName('Les-Tilleuls.coop');
$organization->setMembers([$member]);

$member->setOrganization($organization);

echo $serializer->serialize($organization, 'json'); // Throws a CircularReferenceException

The key circular_reference_limit in the default context sets the number of times it will serialize the same object before considering it a circular reference. The default value is 1.

Instead of throwing an exception, circular references can also be handled by custom callables. This is especially useful when serializing entities having unique identifiers:

1
2
3
4
5
6
7
8
9
10
11
$encoder = new JsonEncoder();
$defaultContext = [
    AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function (object $object, ?string $format, array $context): string {
        return $object->getName();
    },
];
$normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);

$serializer = new Serializer([$normalizer], [$encoder]);
var_dump($serializer->serialize($org, 'json'));
// {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}

Handling Serialization Depth

The Serializer component is able to detect and limit the serialization depth. It is especially useful when serializing large trees. Assume the following data structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace Acme;

class MyObj
{
    public string $foo;

    /**
     * @var self
     */
    public MyObj $child;
}

$level1 = new MyObj();
$level1->foo = 'level1';

$level2 = new MyObj();
$level2->foo = 'level2';
$level1->child = $level2;

$level3 = new MyObj();
$level3->foo = 'level3';
$level2->child = $level3;

The serializer can be configured to set a maximum depth for a given property. Here, we set it to 2 for the $child property:

1
2
3
4
5
6
7
8
9
10
11
namespace Acme;

use Symfony\Component\Serializer\Annotation\MaxDepth;

class MyObj
{
    #[MaxDepth(2)]
    public MyObj $child;

    // ...
}

The metadata loader corresponding to the chosen format must be configured in order to use this feature. It is done automatically when using the Serializer component in a Symfony application. When using the standalone component, refer to the groups documentation to learn how to do that.

The check is only done if the AbstractObjectNormalizer::ENABLE_MAX_DEPTH key of the serializer context is set to true. In the following example, the third level is not serialized because it is deeper than the configured maximum depth of 2:

1
2
3
4
5
6
7
8
9
10
11
12
$result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]);
/*
$result = [
    'foo' => 'level1',
    'child' => [
        'foo' => 'level2',
        'child' => [
            'child' => null,
        ],
    ],
];
*/

Instead of throwing an exception, a custom callable can be executed when the maximum depth is reached. This is especially useful when serializing entities having unique identifiers:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use Symfony\Component\Serializer\Annotation\MaxDepth;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class Foo
{
    public int $id;

    #[MaxDepth(1)]
    public MyObj $child;
}

$level1 = new Foo();
$level1->id = 1;

$level2 = new Foo();
$level2->id = 2;
$level1->child = $level2;

$level3 = new Foo();
$level3->id = 3;
$level2->child = $level3;

$classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());

// all callback parameters are optional (you can omit the ones you don't use)
$maxDepthHandler = function (object $innerObject, object $outerObject, string $attributeName, ?string $format = null, array $context = []): string {
    return '/foos/'.$innerObject->id;
};

$defaultContext = [
    AbstractObjectNormalizer::MAX_DEPTH_HANDLER => $maxDepthHandler,
];
$normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext);

$serializer = new Serializer([$normalizer]);

$result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]);
/*
$result = [
    'id' => 1,
    'child' => [
        'id' => 2,
        'child' => '/foos/3',
    ],
];
*/

Handling Arrays

The Serializer component is capable of handling arrays of objects as well. Serializing arrays works just like serializing a single object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Acme\Person;

$person1 = new Person();
$person1->setName('foo');
$person1->setAge(99);
$person1->setSportsman(false);

$person2 = new Person();
$person2->setName('bar');
$person2->setAge(33);
$person2->setSportsman(true);

$persons = [$person1, $person2];
$data = $serializer->serialize($persons, 'json');

// $data contains [{"name":"foo","age":99,"sportsman":false},{"name":"bar","age":33,"sportsman":true}]

If you want to deserialize such a structure, you need to add the ArrayDenormalizer to the set of normalizers. By appending [] to the type parameter of the deserialize() method, you indicate that you're expecting an array instead of a single object:

1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer(
    [new GetSetMethodNormalizer(), new ArrayDenormalizer()],
    [new JsonEncoder()]
);

$data = ...; // The serialized data from the previous example
$persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');

Handling Constructor Arguments

If the class constructor defines arguments, as usually happens with Value Objects, the serializer won't be able to create the object if some arguments are missing. In those cases, use the default_constructor_arguments context option:

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
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class MyObj
{
    public function __construct(
        private string $foo,
        private string $bar,
    ) {
    }
}

$normalizer = new ObjectNormalizer();
$serializer = new Serializer([$normalizer]);

$data = $serializer->denormalize(
    ['foo' => 'Hello'],
    'MyObj',
    null,
    [AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [
        'MyObj' => ['foo' => '', 'bar' => ''],
    ]]
);
// $data = new MyObj('Hello', '');

Recursive Denormalization and Type Safety

The Serializer component can use the PropertyInfo Component to denormalize complex types (objects). The type of the class' property will be guessed using the provided extractor and used to recursively denormalize the inner data.

When using this component in a Symfony application, all normalizers are automatically configured to use the registered extractors. When using the component standalone, an implementation of PropertyTypeExtractorInterface, (usually an instance of PropertyInfoExtractor) must be passed as the 4th parameter of the ObjectNormalizer:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
namespace Acme;

use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class ObjectOuter
{
    private ObjectInner $inner;
    private \DateTimeInterface $date;

    public function getInner(): ObjectInner
    {
        return $this->inner;
    }

    public function setInner(ObjectInner $inner): void
    {
        $this->inner = $inner;
    }

    public function getDate(): \DateTimeInterface
    {
        return $this->date;
    }

    public function setDate(\DateTimeInterface $date): void
    {
        $this->date = $date;
    }
}

class ObjectInner
{
    public string $foo;
    public string $bar;
}

$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
$serializer = new Serializer([new DateTimeNormalizer(), $normalizer]);

$obj = $serializer->denormalize(
    ['inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21'],
    'Acme\ObjectOuter'
);

dump($obj->getInner()->foo); // 'foo'
dump($obj->getInner()->bar); // 'bar'
dump($obj->getDate()->format('Y-m-d')); // '1988-01-21'

When a PropertyTypeExtractor is available, the normalizer will also check that the data to denormalize matches the type of the property (even for primitive types). For instance, if a string is provided, but the type of the property is int, an UnexpectedValueException will be thrown. The type enforcement of the properties can be disabled by setting the serializer context option ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT to true.

Serializing Interfaces and Abstract Classes

When dealing with objects that are fairly similar or share properties, you may use interfaces or abstract classes. The Serializer component allows you to serialize and deserialize these objects using a "discriminator class mapping".

The discriminator is the field (in the serialized string) used to differentiate between the possible objects. In practice, when using the Serializer component, pass a ClassDiscriminatorResolverInterface implementation to the ObjectNormalizer.

The Serializer component provides an implementation of ClassDiscriminatorResolverInterface called ClassDiscriminatorFromClassMetadata which uses the class metadata factory and a mapping configuration to serialize and deserialize objects of the correct class.

When using this component inside a Symfony application and the class metadata factory is enabled as explained in the Attributes Groups section, this is already set up and you only need to provide the configuration. Otherwise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ...
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());

$discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory);

$serializer = new Serializer(
    [new ObjectNormalizer($classMetadataFactory, null, null, null, $discriminator)],
    ['json' => new JsonEncoder()]
);

Now configure your discriminator class mapping. Consider an application that defines an abstract CodeRepository class extended by GitHubCodeRepository and BitBucketCodeRepository classes:

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

use App\BitBucketCodeRepository;
use App\GitHubCodeRepository;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;

#[DiscriminatorMap(typeProperty: 'type', mapping: [
    'github' => GitHubCodeRepository::class,
    'bitbucket' => BitBucketCodeRepository::class,
])]
abstract class CodeRepository
{
    // ...
}

Note

The values of the mapping array option must be strings. Otherwise, they will be cast into strings automatically.

Once configured, the serializer uses the mapping to pick the correct class:

1
2
3
4
5
$serialized = $serializer->serialize(new GitHubCodeRepository(), 'json');
// {"type": "github"}

$repository = $serializer->deserialize($serialized, CodeRepository::class, 'json');
// instanceof GitHubCodeRepository

Learn more

See also

Normalizers for the Symfony Serializer Component supporting popular web API formats (JSON-LD, GraphQL, OpenAPI, HAL, JSON:API) are available as part of the API Platform project.

See also

A popular alternative to the Symfony Serializer component is the third-party library, JMS serializer (versions before v1.12.0 were released under the Apache license, so incompatible with GPLv2 projects).

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version