The Serializer Component

The Serializer Component

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.

As you can see in the picture above, an array is used as an intermediary between objects and serialized contents. This way, 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.

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 Symfony\Component\Serializer\Serializer specifying which encoders and normalizer are going to be available:

  1. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  2. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  3. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  4. use Symfony\Component\Serializer\Serializer;
  5. $encoders = [new XmlEncoder(), new JsonEncoder()];
  6. $normalizers = [new ObjectNormalizer()];
  7. $serializer = new Serializer($normalizers, $encoders);

The preferred normalizer is the Symfony\Component\Serializer\Normalizer\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. namespace App\Model;
  2. class Person
  3. {
  4. private $age;
  5. private $name;
  6. private $sportsperson;
  7. private $createdAt;
  8. // Getters
  9. public function getName()
  10. {
  11. return $this->name;
  12. }
  13. public function getAge()
  14. {
  15. return $this->age;
  16. }
  17. public function getCreatedAt()
  18. {
  19. return $this->createdAt;
  20. }
  21. // Issers
  22. public function isSportsperson()
  23. {
  24. return $this->sportsperson;
  25. }
  26. // Setters
  27. public function setName($name)
  28. {
  29. $this->name = $name;
  30. }
  31. public function setAge($age)
  32. {
  33. $this->age = $age;
  34. }
  35. public function setSportsperson($sportsperson)
  36. {
  37. $this->sportsperson = $sportsperson;
  38. }
  39. public function setCreatedAt($createdAt)
  40. {
  41. $this->createdAt = $createdAt;
  42. }
  43. }

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

  1. use App\Model\Person;
  2. $person = new Person();
  3. $person->setName('foo');
  4. $person->setAge(99);
  5. $person->setSportsperson(false);
  6. $jsonContent = $serializer->serialize($person, 'json');
  7. // $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}
  8. 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 Symfony\Component\Serializer\Encoder\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. use App\Model\Person;
  2. $data = <<<EOF
  3. <person>
  4. <name>foo</name>
  5. <age>99</age>
  6. <sportsperson>false</sportsperson>
  7. </person>
  8. EOF;
  9. $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. use App\Model\Person;
  2. $data = <<<EOF
  3. <person>
  4. <name>foo</name>
  5. <age>99</age>
  6. <city>Paris</city>
  7. </person>
  8. EOF;
  9. // $loader is any of the valid loaders explained later in this article
  10. $classMetadataFactory = new ClassMetadataFactory($loader);
  11. $normalizer = new ObjectNormalizer($classMetadataFactory);
  12. $serializer = new Serializer([$normalizer]);
  13. // this will throw a Symfony\Component\Serializer\Exception\ExtraAttributesException
  14. // because "city" is not an attribute of the Person class
  15. $person = $serializer->deserialize($data, Person::class, 'xml', [
  16. AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false,
  17. ]);

Deserializing in an Existing Object

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

  1. // ...
  2. $person = new Person();
  3. $person->setName('bar');
  4. $person->setAge(99);
  5. $person->setSportsperson(true);
  6. $data = <<<EOF
  7. <person>
  8. <name>foo</name>
  9. <age>69</age>
  10. </person>
  11. EOF;
  12. $serializer->deserialize($data, Person::class, 'xml', [AbstractNormalizer::OBJECT_TO_POPULATE => $person]);
  13. // $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.

New in version 4.3: The AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE option was introduced in Symfony 4.3.

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. namespace Acme;
  2. class MyObj
  3. {
  4. public $foo;
  5. private $bar;
  6. public function getBar()
  7. {
  8. return $this->bar;
  9. }
  10. public function setBar($bar)
  11. {
  12. return $this->bar = $bar;
  13. }
  14. }

The definition of serialization can be specified using annotations, XML or YAML. The Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory that will be used by the normalizer must be aware of the format to use.

The following code shows how to initialize the Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory for each format:

  • Annotations in PHP files:

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

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

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

Then, create your groups definition:

  • Annotations

    1. namespace Acme;
    2. use Symfony\Component\Serializer\Annotation\Groups;
    3. class MyObj
    4. {
    5. /**
    6. * @Groups({"group1", "group2"})
    7. */
    8. public $foo;
    9. /**
    10. * @Groups("group3")
    11. */
    12. public function getBar() // is* methods are also supported
    13. {
    14. return $this->bar;
    15. }
    16. // ...
    17. }
  • YAML

    1. Acme\MyObj:
    2. attributes:
    3. foo:
    4. groups: ['group1', 'group2']
    5. bar:
    6. groups: ['group3']
  • XML

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
    5. https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
    6. >
    7. <class name="Acme\MyObj">
    8. <attribute name="foo">
    9. <group>group1</group>
    10. <group>group2</group>
    11. </attribute>
    12. <attribute name="bar">
    13. <group>group3</group>
    14. </attribute>
    15. </class>
    16. </serializer>

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

  1. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  2. use Symfony\Component\Serializer\Serializer;
  3. $obj = new MyObj();
  4. $obj->foo = 'foo';
  5. $obj->setBar('bar');
  6. $normalizer = new ObjectNormalizer($classMetadataFactory);
  7. $serializer = new Serializer([$normalizer]);
  8. $data = $serializer->normalize($obj, null, ['groups' => 'group1']);
  9. // $data = ['foo' => 'foo'];
  10. $obj2 = $serializer->denormalize(
  11. ['foo' => 'foo', 'bar' => 'bar'],
  12. 'MyObj',
  13. null,
  14. ['groups' => ['group1', 'group3']]
  15. );
  16. // $obj2 = MyObj(foo: 'foo', bar: 'bar')

Selecting Specific Attributes

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

  1. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  2. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  3. use Symfony\Component\Serializer\Serializer;
  4. class User
  5. {
  6. public $familyName;
  7. public $givenName;
  8. public $company;
  9. }
  10. class Company
  11. {
  12. public $name;
  13. public $address;
  14. }
  15. $company = new Company();
  16. $company->name = 'Les-Tilleuls.coop';
  17. $company->address = 'Lille, France';
  18. $user = new User();
  19. $user->familyName = 'Dunglas';
  20. $user->givenName = 'Kévin';
  21. $user->company = $company;
  22. $serializer = new Serializer([new ObjectNormalizer()]);
  23. $data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
  24. // $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 process.

Ignoring Attributes

As an option, there’s a way to ignore attributes from the origin object. To remove those attributes provide an array via the AbstractNormalizer::IGNORED_ATTRIBUTES key in the context parameter of the desired serializer method:

  1. use Acme\Person;
  2. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  3. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  4. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  5. use Symfony\Component\Serializer\Serializer;
  6. $person = new Person();
  7. $person->setName('foo');
  8. $person->setAge(99);
  9. $normalizer = new ObjectNormalizer();
  10. $encoder = new JsonEncoder();
  11. $serializer = new Serializer([$normalizer], [$encoder]);
  12. $serializer->serialize($person, 'json', [AbstractNormalizer::IGNORED_ATTRIBUTES => ['age']]); // Output: {"name":"foo"}

Deprecated since version 4.2: The setIgnoredAttributes() method that was used as an alternative to the AbstractNormalizer::IGNORED_ATTRIBUTES option was deprecated in Symfony 4.2.

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. class Company
  2. {
  3. public $name;
  4. public $address;
  5. }

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. use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
  2. class OrgPrefixNameConverter implements NameConverterInterface
  3. {
  4. public function normalize($propertyName)
  5. {
  6. return 'org_'.$propertyName;
  7. }
  8. public function denormalize($propertyName)
  9. {
  10. // removes 'org_' prefix
  11. return 'org_' === substr($propertyName, 0, 4) ? substr($propertyName, 4) : $propertyName;
  12. }
  13. }

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

  1. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  2. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  3. use Symfony\Component\Serializer\Serializer;
  4. $nameConverter = new OrgPrefixNameConverter();
  5. $normalizer = new ObjectNormalizer(null, $nameConverter);
  6. $serializer = new Serializer([$normalizer], [new JsonEncoder()]);
  7. $company = new Company();
  8. $company->name = 'Acme Inc.';
  9. $company->address = '123 Main Street, Big City';
  10. $json = $serializer->serialize($company, 'json');
  11. // {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}
  12. $companyCopy = $serializer->deserialize($json, Company::class, 'json');
  13. // Same data as $company

Note

You can also implement Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface to access to 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. use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
  2. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  3. $normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter());
  4. class Person
  5. {
  6. private $firstName;
  7. public function __construct($firstName)
  8. {
  9. $this->firstName = $firstName;
  10. }
  11. public function getFirstName()
  12. {
  13. return $this->firstName;
  14. }
  15. }
  16. $kevin = new Person('Kévin');
  17. $normalizer->normalize($kevin);
  18. // ['first_name' => 'Kévin'];
  19. $anne = $normalizer->denormalize(['first_name' => 'Anne'], 'Person');
  20. // 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. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  3. use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
  4. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  5. use Symfony\Component\Serializer\Serializer;
  6. $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
  7. $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
  8. $serializer = new Serializer(
  9. [new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
  10. ['json' => new JsonEncoder()]
  11. );

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

  • Annotations

    1. namespace App\Entity;
    2. use Symfony\Component\Serializer\Annotation\SerializedName;
    3. class Person
    4. {
    5. /**
    6. * @SerializedName("customer_name")
    7. */
    8. private $firstName;
    9. public function __construct($firstName)
    10. {
    11. $this->firstName = $firstName;
    12. }
    13. // ...
    14. }
  • YAML

    1. App\Entity\Person:
    2. attributes:
    3. firstName:
    4. serialized_name: customer_name
  • XML

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
    5. https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
    6. >
    7. <class name="App\Entity\Person">
    8. <attribute name="firstName" serialized-name="customer_name"/>
    9. </class>
    10. </serializer>

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

  1. $serialized = $serializer->serialize(new Person('Kévin'), 'json');
  2. // {"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, add and remove.

Using Callbacks to Serialize Properties with Object Instances

Deprecated since version 4.2: The setCallbacks() method is deprecated since Symfony 4.2. Use the callbacks key of the context instead.

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

  1. use App\Model\Person;
  2. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  3. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  4. use Symfony\Component\Serializer\Serializer;
  5. $encoder = new JsonEncoder();
  6. // all callback parameters are optional (you can omit the ones you don't use)
  7. $dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
  8. return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
  9. };
  10. $defaultContext = [
  11. AbstractNormalizer::CALLBACKS => [
  12. 'createdAt' => $dateCallback,
  13. ],
  14. ];
  15. $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
  16. $serializer = new Serializer([$normalizer], [$encoder]);
  17. $person = new Person();
  18. $person->setName('cordoval');
  19. $person->setAge(34);
  20. $person->setCreatedAt(new \DateTime('now'));
  21. $serializer->serialize($person, 'json');
  22. // Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}

Deprecated since version 4.2: The setCallbacks() is deprecated since Symfony 4.2, use the “callbacks” key of the context instead.

Normalizers

Normalizers turn object into array and vice versa. They implement :Symfony\Component\Serializer\Normalizer\NormalizableInterface for normalize (object to array) and Symfony\Component\Serializer\Normalizer\DenormalizableInterface for denormalize (array to object).

You can add new normalizers to a Serializer instance by using its first constructor argument:

  1. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  2. use Symfony\Component\Serializer\Serializer;
  3. $normalizers = [new ObjectNormalizer()];
  4. $serializer = new Serializer($normalizers, []);

Built-in Normalizers

The Serializer component provides several built-in normalizers:

Symfony\Component\Serializer\Normalizer\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, 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, add or remove prefix from the method name and transforming the first letter to lowercase; e.g. getFirstName() -&gt;firstName`).

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

Symfony\Component\Serializer\Normalizer\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() -&gt;firstName`).

Symfony\Component\Serializer\Normalizer\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). It supports calling the constructor during the denormalization process.

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

Symfony\Component\Serializer\Normalizer\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.

Symfony\Component\Serializer\Normalizer\DateTimeNormalizer

This normalizer converts DateTimeInterface objects (e.g. DateTime and DateTimeImmutable) into strings. By default, it uses the RFC3339 format.

Symfony\Component\Serializer\Normalizer\DateTimeZoneNormalizer

This normalizer converts DateTimeZone objects into strings that represent the name of the timezone according to the list of PHP timezones.

New in version 4.3: The DateTimeZoneNormalizer was introduced in Symfony 4.3.

Symfony\Component\Serializer\Normalizer\DataUriNormalizer

This normalizer converts SplFileInfo objects into a data URI string (data:...) such that files can be embedded into serialized data.

Symfony\Component\Serializer\Normalizer\DateIntervalNormalizer

This normalizer converts DateInterval objects into strings. By default, it uses the P%yY%mM%dDT%hH%iM%sS format.

Symfony\Component\Serializer\Normalizer\ConstraintViolationListNormalizer

This normalizer converts objects that implement Symfony\Component\Validator\ConstraintViolationListInterface into a list of errors according to the RFC 7807 standard.

Symfony\Component\Serializer\Normalizer\ProblemNormalizer

Normalizes errors according to the API Problem spec RFC 7807.

Symfony\Component\Serializer\Normalizer\CustomNormalizer

Normalizes a PHP object using an object that implements Symfony\Component\Serializer\Normalizer\NormalizableInterface.

Note

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

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

Encoders

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

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

  1. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  2. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  3. use Symfony\Component\Serializer\Serializer;
  4. $encoders = [new XmlEncoder(), new JsonEncoder()];
  5. $serializer = new Serializer([], $encoders);

Built-in Encoders

The Serializer component provides several built-in encoders:

Symfony\Component\Serializer\Encoder\JsonEncoder

This class encodes and decodes data in JSON.

Symfony\Component\Serializer\Encoder\XmlEncoder

This class encodes and decodes data in XML.

Symfony\Component\Serializer\Encoder\YamlEncoder

This encoder encodes and decodes data in YAML. This encoder requires the Yaml Component.

Symfony\Component\Serializer\Encoder\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]);

The CsvEncoder

The CsvEncoder encodes to and decodes from CSV.

The CsvEncoder Context Options

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

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

These are the options available:

OptionDescriptionDefault
csv_delimiterSets the field delimiter separating values (one character only),
csv_enclosureSets the field enclosure (one character only)
csv_escape_charSets the escape character (at most one character)empty string
csv_key_separatorSets the separator for array’s keys during its flattening.
csv_headersSets 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_formulasEscapes fields containg formulas by prepending them with a \t characterfalse
as_collectionAlways returns results as a collection, even if only one line is decoded.true
no_headersDisables header in the encoded CSVfalse
output_utf8_bomOutputs special UTF-8 BOM along with encoded datafalse

New in version 4.4: The output_utf8_bom option was introduced in Symfony 4.4.

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. <?xml version="1.0" encoding="UTF-8" ?>
  2. <response>
  3. <foo>1</foo>
  4. <foo>2</foo>
  5. <bar>1</bar>
  6. </response>

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

  1. ['foo' => ['@bar' => 'value', '#' => 'baz']];
  2. // is encoded as follows:
  3. // <?xml version="1.0"?>
  4. // <response>
  5. // <foo bar="value">
  6. // baz
  7. // </foo>
  8. // </response>

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

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

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

Tip

XML comments are ignored by default when decoding contents, but this behavior can be changed with the optional $decoderIgnoredNodeTypes argument of the XmlEncoder class constructor.

Data with #comment keys are encoded to XML comments by default. This can be changed with the optional $encoderIgnoredNodeTypes argument of the XmlEncoder class constructor.

The XmlEncoder Context Options

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

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

These are the options available:

OptionDescriptionDefault
xmlformat_outputIf set to true, formats the generated XML with line breaks and indentationfalse
xml_versionSets the XML version attribute1.1
xml_encodingSets the XML encoding attributeutf-8
xml_standaloneAdds standalone attribute in the generated XMLtrue
xml_type_cast_attributesThis provides the ability to forgot the attribute type castingtrue
xml_root_node_nameSets the root node nameresponse
as_collectionAlways returns results as a collection, even if only one line is decodedfalse
decoder_ignored_node_typesArray of node types (DOM XML constants) to be ignored while decoding[\XMLPI_NODE, \XML_COMMENT_NODE]
encoder_ignored_node_typesArray of node types (DOM XML constants) to be ignored while encoding[]
load_optionsXML loading options with libxml\LIBXML_NONET | \LIBXML_NOBLANKS
remove_empty_tagsIf set to true, removes all empty tags in the generated XMLfalse

New in version 4.2: The decoder_ignored_node_types and encoder_ignored_node_types options were introduced in Symfony 4.2.

Example with custom context:

  1. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  2. // create encoder with specified options as new default settings
  3. $xmlEncoder = new XmlEncoder(['xml_format_output' => true]);
  4. $data = [
  5. 'id' => 'IDHNQIItNyQ',
  6. 'date' => '2019-10-24',
  7. ];
  8. // encode with default context
  9. $xmlEncoder->encode($data, 'xml');
  10. // outputs:
  11. // <?xml version="1.0"?>
  12. // <response>
  13. // <id>IDHNQIItNyQ</id>
  14. // <date>2019-10-24</date>
  15. // </response>
  16. // encode with modified context
  17. $xmlEncoder->encode($data, 'xml', [
  18. 'xml_root_node_name' => 'track',
  19. 'encoder_ignored_node_types' => [
  20. \XML_PI_NODE, // removes XML declaration (the leading xml tag)
  21. ],
  22. ]);
  23. // outputs:
  24. // <track>
  25. // <id>IDHNQIItNyQ</id>
  26. // <date>2019-10-24</date>
  27. // </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, usescontext` to set configuration options for the YamlEncoder an associative array:

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

These are the options available:

OptionDescriptionDefault
yamlinlineThe level where you switch to inline YAML0
yaml_indentThe level of indentation (used internally)0
yaml_flagsA bit field of Yaml::DUMP / PARSE_ constants to customize the encoding / decoding YAML string0

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. $dummy = new class {
  2. public $foo;
  3. public $bar = 'notNull';
  4. };
  5. $normalizer = new ObjectNormalizer();
  6. $result = $normalizer->normalize($dummy, 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]);
  7. // ['bar' => 'notNull']

Handling Circular References

Circular references are common when dealing with entity relations:

  1. class Organization
  2. {
  3. private $name;
  4. private $members;
  5. public function setName($name)
  6. {
  7. $this->name = $name;
  8. }
  9. public function getName()
  10. {
  11. return $this->name;
  12. }
  13. public function setMembers(array $members)
  14. {
  15. $this->members = $members;
  16. }
  17. public function getMembers()
  18. {
  19. return $this->members;
  20. }
  21. }
  22. class Member
  23. {
  24. private $name;
  25. private $organization;
  26. public function setName($name)
  27. {
  28. $this->name = $name;
  29. }
  30. public function getName()
  31. {
  32. return $this->name;
  33. }
  34. public function setOrganization(Organization $organization)
  35. {
  36. $this->organization = $organization;
  37. }
  38. public function getOrganization()
  39. {
  40. return $this->organization;
  41. }
  42. }

To avoid infinite loops, Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer or Symfony\Component\Serializer\Normalizer\ObjectNormalizer throw a Symfony\Component\Serializer\Exception\CircularReferenceException when such a case is encountered:

  1. $member = new Member();
  2. $member->setName('Kévin');
  3. $organization = new Organization();
  4. $organization->setName('Les-Tilleuls.coop');
  5. $organization->setMembers([$member]);
  6. $member->setOrganization($organization);
  7. 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. $encoder = new JsonEncoder();
  2. $defaultContext = [
  3. AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
  4. return $object->getName();
  5. },
  6. ];
  7. $normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);
  8. $serializer = new Serializer([$normalizer], [$encoder]);
  9. var_dump($serializer->serialize($org, 'json'));
  10. // {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}

Deprecated since version 4.2: The setCircularReferenceHandler() method is deprecated since Symfony 4.2. Use the AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER key of the context instead.

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. namespace Acme;
  2. class MyObj
  3. {
  4. public $foo;
  5. /**
  6. * @var self
  7. */
  8. public $child;
  9. }
  10. $level1 = new MyObj();
  11. $level1->foo = 'level1';
  12. $level2 = new MyObj();
  13. $level2->foo = 'level2';
  14. $level1->child = $level2;
  15. $level3 = new MyObj();
  16. $level3->foo = 'level3';
  17. $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:

  • Annotations

    1. namespace Acme;
    2. use Symfony\Component\Serializer\Annotation\MaxDepth;
    3. class MyObj
    4. {
    5. /**
    6. * @MaxDepth(2)
    7. */
    8. public $child;
    9. // ...
    10. }
  • YAML

    1. Acme\MyObj:
    2. attributes:
    3. child:
    4. max_depth: 2
  • XML

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
    5. https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
    6. >
    7. <class name="Acme\MyObj">
    8. <attribute name="child" max-depth="2"/>
    9. </class>
    10. </serializer>

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

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. use Doctrine\Common\Annotations\AnnotationReader;
  2. use Symfony\Component\Serializer\Annotation\MaxDepth;
  3. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
  4. use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
  5. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  6. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  7. use Symfony\Component\Serializer\Serializer;
  8. class Foo
  9. {
  10. public $id;
  11. /**
  12. * @MaxDepth(1)
  13. */
  14. public $child;
  15. }
  16. $level1 = new Foo();
  17. $level1->id = 1;
  18. $level2 = new Foo();
  19. $level2->id = 2;
  20. $level1->child = $level2;
  21. $level3 = new Foo();
  22. $level3->id = 3;
  23. $level2->child = $level3;
  24. $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
  25. // all callback parameters are optional (you can omit the ones you don't use)
  26. $maxDepthHandler = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
  27. return '/foos/'.$innerObject->id;
  28. };
  29. $defaultContext = [
  30. AbstractObjectNormalizer::MAX_DEPTH_HANDLER => $maxDepthHandler,
  31. ];
  32. $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext);
  33. $serializer = new Serializer([$normalizer]);
  34. $result = $serializer->normalize($level1, null, [AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true]);
  35. /*
  36. $result = [
  37. 'id' => 1,
  38. 'child' => [
  39. 'id' => 2,
  40. 'child' => '/foos/3',
  41. ],
  42. ];
  43. */

Deprecated since version 4.2: The setMaxDepthHandler() method is deprecated since Symfony 4.2. Use the max_depth_handler key of the context instead.

Handling Arrays

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

  1. use Acme\Person;
  2. $person1 = new Person();
  3. $person1->setName('foo');
  4. $person1->setAge(99);
  5. $person1->setSportsman(false);
  6. $person2 = new Person();
  7. $person2->setName('bar');
  8. $person2->setAge(33);
  9. $person2->setSportsman(true);
  10. $persons = [$person1, $person2];
  11. $data = $serializer->serialize($persons, 'json');
  12. // $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 Symfony\Component\Serializer\Normalizer\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. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  2. use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
  3. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  4. use Symfony\Component\Serializer\Serializer;
  5. $serializer = new Serializer(
  6. [new GetSetMethodNormalizer(), new ArrayDenormalizer()],
  7. [new JsonEncoder()]
  8. );
  9. $data = ...; // The serialized data from the previous example
  10. $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. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  2. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  3. use Symfony\Component\Serializer\Serializer;
  4. class MyObj
  5. {
  6. private $foo;
  7. private $bar;
  8. public function __construct($foo, $bar)
  9. {
  10. $this->foo = $foo;
  11. $this->bar = $bar;
  12. }
  13. }
  14. $normalizer = new ObjectNormalizer($classMetadataFactory);
  15. $serializer = new Serializer([$normalizer]);
  16. $data = $serializer->denormalize(
  17. ['foo' => 'Hello'],
  18. 'MyObj',
  19. null,
  20. [AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [
  21. 'MyObj' => ['foo' => '', 'bar' => ''],
  22. ]]
  23. );
  24. // $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 Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface, (usually an instance of Symfony\Component\PropertyInfo\PropertyInfoExtractor) must be passed as the 4th parameter of the ObjectNormalizer:

  1. namespace Acme;
  2. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  3. use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
  4. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  5. use Symfony\Component\Serializer\Serializer;
  6. class ObjectOuter
  7. {
  8. private $inner;
  9. private $date;
  10. public function getInner()
  11. {
  12. return $this->inner;
  13. }
  14. public function setInner(ObjectInner $inner)
  15. {
  16. $this->inner = $inner;
  17. }
  18. public function setDate(\DateTimeInterface $date)
  19. {
  20. $this->date = $date;
  21. }
  22. public function getDate()
  23. {
  24. return $this->date;
  25. }
  26. }
  27. class ObjectInner
  28. {
  29. public $foo;
  30. public $bar;
  31. }
  32. $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
  33. $serializer = new Serializer([new DateTimeNormalizer(), $normalizer]);
  34. $obj = $serializer->denormalize(
  35. ['inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21'],
  36. 'Acme\ObjectOuter'
  37. );
  38. dump($obj->getInner()->foo); // 'foo'
  39. dump($obj->getInner()->bar); // 'bar'
  40. 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 Symfony\Component\Serializer\Exception\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 Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface implementation to the Symfony\Component\Serializer\Normalizer\ObjectNormalizer.

The Serializer component provides an implementation of ClassDiscriminatorResolverInterface called Symfony\Component\Serializer\Mapping\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. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  3. use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
  4. use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
  5. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  6. use Symfony\Component\Serializer\Serializer;
  7. $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
  8. $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory);
  9. $serializer = new Serializer(
  10. [new ObjectNormalizer($classMetadataFactory, null, null, null, $discriminator)],
  11. ['json' => new JsonEncoder()]
  12. );

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

  • Annotations

    1. namespace App;
    2. use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
    3. /**
    4. * @DiscriminatorMap(typeProperty="type", mapping={
    5. * "github"="App\GitHubCodeRepository",
    6. * "bitbucket"="App\BitBucketCodeRepository"
    7. * })
    8. */
    9. abstract class CodeRepository
    10. {
    11. // ...
    12. }
  • YAML

    1. App\CodeRepository:
    2. discriminator_map:
    3. type_property: type
    4. mapping:
    5. github: 'App\GitHubCodeRepository'
    6. bitbucket: 'App\BitBucketCodeRepository'
  • XML

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
    5. https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
    6. >
    7. <class name="App\CodeRepository">
    8. <discriminator-map type-property="type">
    9. <mapping type="github" class="App\GitHubCodeRepository"/>
    10. <mapping type="bitbucket" class="App\BitBucketCodeRepository"/>
    11. </discriminator-map>
    12. </class>
    13. </serializer>

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

  1. $serialized = $serializer->serialize(new GitHubCodeRepository(), 'json');
  2. // {"type": "github"}
  3. $repository = $serializer->deserialize($serialized, CodeRepository::class, 'json');
  4. // 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.