The Serializer Component

The Serializer component is meant to be used to turn objects into aspecific 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 betweenobjects and serialized contents. This way, encoders will only deal with turningspecific formats into arrays and vice versa. The same way, Normalizerswill 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 mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

To use the ObjectNormalizer, the PropertyAccess componentmust also be installed.

Usage

This article explains the philosophy of the Serializer and gets you familiarwith the concepts of normalizers and encoders. The code examples assumethat you use the Serializer as an independent component. If you are usingthe Serializer in a Symfony application, read How to Use the Serializer after youfinish this article.

To use the Serializer component, set up theSerializer specifying which encodersand 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.  
  6. $encoders = [new XmlEncoder(), new JsonEncoder()];
  7. $normalizers = [new ObjectNormalizer()];
  8.  
  9. $serializer = new Serializer($normalizers, $encoders);

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

Serializing an Object

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

  1. namespace App\Model;
  2.  
  3. class Person
  4. {
  5. private $age;
  6. private $name;
  7. private $sportsperson;
  8. private $createdAt;
  9.  
  10. // Getters
  11. public function getName()
  12. {
  13. return $this->name;
  14. }
  15.  
  16. public function getAge()
  17. {
  18. return $this->age;
  19. }
  20.  
  21. public function getCreatedAt()
  22. {
  23. return $this->createdAt;
  24. }
  25.  
  26. // Issers
  27. public function isSportsperson()
  28. {
  29. return $this->sportsperson;
  30. }
  31.  
  32. // Setters
  33. public function setName($name)
  34. {
  35. $this->name = $name;
  36. }
  37.  
  38. public function setAge($age)
  39. {
  40. $this->age = $age;
  41. }
  42.  
  43. public function setSportsperson($sportsperson)
  44. {
  45. $this->sportsperson = $sportsperson;
  46. }
  47.  
  48. public function setCreatedAt($createdAt)
  49. {
  50. $this->createdAt = $createdAt;
  51. }
  52. }

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

  1. $person = new App\Model\Person();
  2. $person->setName('foo');
  3. $person->setAge(99);
  4. $person->setSportsperson(false);
  5.  
  6. $jsonContent = $serializer->serialize($person, 'json');
  7.  
  8. // $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}
  9.  
  10. 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 informationof the Person class would be encoded in XML format:

  1. use App\Model\Person;
  2.  
  3. $data = <<<EOF
  4. <person>
  5. <name>foo</name>
  6. <age>99</age>
  7. <sportsperson>false</sportsperson>
  8. </person>
  9. EOF;
  10.  
  11. $person = $serializer->deserialize($data, Person::class, 'xml');

In this case, deserialize()needs three parameters:

  • The information to be decoded
  • The name of the class this information will be decoded to
  • The encoder used to convert that information into an arrayBy default, additional attributes that are not mapped to the denormalized objectwill be ignored by the Serializer component. If you prefer to throw an exceptionwhen this happens, set the allow_extra_attributes context option tofalse and provide an object that implements ClassMetadataFactoryInterfacewhen constructing the normalizer:
  1. $data = <<<EOF
  2. <person>
  3. <name>foo</name>
  4. <age>99</age>
  5. <city>Paris</city>
  6. </person>
  7. EOF;
  8.  
  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.  
  14. // this will throw a Symfony\Component\Serializer\Exception\ExtraAttributesException
  15. // because "city" is not an attribute of the Person class
  16. $person = $serializer->deserialize($data, 'App\Model\Person', 'xml', [
  17. 'allow_extra_attributes' => false,
  18. ]);

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.  
  7. $data = <<<EOF
  8. <person>
  9. <name>foo</name>
  10. <age>69</age>
  11. </person>
  12. EOF;
  13.  
  14. $serializer->deserialize($data, Person::class, 'xml', ['object_to_populate' => $person]);
  15. // $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true)

This is a common need when working with an ORM.

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

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

New in version 4.3: The AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE option wasintroduced in Symfony 4.3.

Attributes Groups

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

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

  1. namespace Acme;
  2.  
  3. class MyObj
  4. {
  5. public $foo;
  6.  
  7. private $bar;
  8.  
  9. public function getBar()
  10. {
  11. return $this->bar;
  12. }
  13.  
  14. public function setBar($bar)
  15. {
  16. return $this->bar = $bar;
  17. }
  18. }

The definition of serialization can be specified using annotations, XMLor YAML. The ClassMetadataFactorythat will be used by the normalizer must be aware of the format to use.

The following code shows how to initialize the ClassMetadataFactoryfor 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.  
  5. $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.  
  4. $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.  
  4. $classMetadataFactory = new ClassMetadataFactory(new XmlFileLoader('/path/to/your/definition.xml'));

Then, create your groups definition:

  • Annotations
  1. namespace Acme;
  2.  
  3. use Symfony\Component\Serializer\Annotation\Groups;
  4.  
  5. class MyObj
  6. {
  7. /**
  8. * @Groups({"group1", "group2"})
  9. */
  10. public $foo;
  11.  
  12. /**
  13. * @Groups("group3")
  14. */
  15. public function getBar() // is* methods are also supported
  16. {
  17. return $this->bar;
  18. }
  19.  
  20. // ...
  21. }
  • YAML
  1. Acme\MyObj:
  2. attributes:
  3. foo:
  4. groups: ['group1', 'group2']
  5. bar:
  6. groups: ['group3']
  • XML
  1. <?xml version="1.0" ?>
  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.  
  13. <attribute name="bar">
  14. <group>group3</group>
  15. </attribute>
  16. </class>
  17. </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.  
  4. $obj = new MyObj();
  5. $obj->foo = 'foo';
  6. $obj->setBar('bar');
  7.  
  8. $normalizer = new ObjectNormalizer($classMetadataFactory);
  9. $serializer = new Serializer([$normalizer]);
  10.  
  11. $data = $serializer->normalize($obj, null, ['groups' => 'group1']);
  12. // $data = ['foo' => 'foo'];
  13.  
  14. $obj2 = $serializer->denormalize(
  15. ['foo' => 'foo', 'bar' => 'bar'],
  16. 'MyObj',
  17. null,
  18. ['groups' => ['group1', 'group3']]
  19. );
  20. // $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\ObjectNormalizer;
  2. use Symfony\Component\Serializer\Serializer;
  3.  
  4. class User
  5. {
  6. public $familyName;
  7. public $givenName;
  8. public $company;
  9. }
  10.  
  11. class Company
  12. {
  13. public $name;
  14. public $address;
  15. }
  16.  
  17. $company = new Company();
  18. $company->name = 'Les-Tilleuls.coop';
  19. $company->address = 'Lille, France';
  20.  
  21. $user = new User();
  22. $user->familyName = 'Dunglas';
  23. $user->givenName = 'Kévin';
  24. $user->company = $company;
  25.  
  26. $serializer = new Serializer([new ObjectNormalizer()]);
  27.  
  28. $data = $serializer->normalize($user, null, ['attributes' => ['familyName', 'company' => ['name']]]);
  29. // $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 ignored_attributeskey 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\ObjectNormalizer;
  4. use Symfony\Component\Serializer\Serializer;
  5.  
  6. $person = new Person();
  7. $person->setName('foo');
  8. $person->setAge(99);
  9.  
  10. $normalizer = new ObjectNormalizer();
  11. $encoder = new JsonEncoder();
  12.  
  13. $serializer = new Serializer([$normalizer], [$encoder]);
  14. $serializer->serialize($person, 'json', ['ignored_attributes' => ['age']]); // Output: {"name":"foo"}

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

Converting Property Names when Serializing and Deserializing

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

The Serializer component provides a handy way to translate or map PHP fieldnames 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_ likethe 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.  
  3. class OrgPrefixNameConverter implements NameConverterInterface
  4. {
  5. public function normalize($propertyName)
  6. {
  7. return 'org_'.$propertyName;
  8. }
  9.  
  10. public function denormalize($propertyName)
  11. {
  12. // removes 'org_' prefix
  13. return 'org_' === substr($propertyName, 0, 4) ? substr($propertyName, 4) : $propertyName;
  14. }
  15. }

The custom name converter can be used by passing it as second parameter of anyclass extending AbstractNormalizer,including GetSetMethodNormalizerand PropertyNormalizer:

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

Note

You can also implementAdvancedNameConverterInterfaceto 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 knownas snake_case). However, in Symfony applications is common to use CamelCase toname properties (even though the PSR-1 standard doesn't recommend anyspecific case for property names).

Symfony provides a built-in name converter designed to transform betweensnake_case and CamelCased styles during serialization and deserializationprocesses:

  1. use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
  2. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  3.  
  4. $normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter());
  5.  
  6. class Person
  7. {
  8. private $firstName;
  9.  
  10. public function __construct($firstName)
  11. {
  12. $this->firstName = $firstName;
  13. }
  14.  
  15. public function getFirstName()
  16. {
  17. return $this->firstName;
  18. }
  19. }
  20.  
  21. $kevin = new Person('Kévin');
  22. $normalizer->normalize($kevin);
  23. // ['first_name' => 'Kévin'];
  24.  
  25. $anne = $normalizer->denormalize(['first_name' => 'Anne'], 'Person');
  26. // Person object with firstName: 'Anne'

Configure name conversion using metadata

When using this component inside a Symfony application and the class metadatafactory 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.  
  7. $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
  8.  
  9. $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
  10.  
  11. $serializer = new Serializer(
  12. [new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
  13. ['json' => new JsonEncoder()]
  14. );

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

  • Annotations
  1. namespace App\Entity;
  2.  
  3. use Symfony\Component\Serializer\Annotation\SerializedName;
  4.  
  5. class Person
  6. {
  7. /**
  8. * @SerializedName("customer_name")
  9. */
  10. private $firstName;
  11.  
  12. public function __construct($firstName)
  13. {
  14. $this->firstName = $firstName;
  15. }
  16.  
  17. // ...
  18. }
  • YAML
  1. App\Entity\Person:
  2. attributes:
  3. firstName:
  4. serialized_name: customer_name
  • XML
  1. <?xml version="1.0" ?>
  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 anddeserializing objects:

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

Serializing Boolean Attributes

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

The ObjectNormalizer also takes care of methods starting with has, addand 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 callbackskey 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.  
  6. $encoder = new JsonEncoder();
  7.  
  8. // all callback parameters are optional (you can omit the ones you don't use)
  9. $dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
  10. return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
  11. };
  12.  
  13. $defaultContext = [
  14. AbstractNormalizer::CALLBACKS => [
  15. 'createdAt' => $dateCallback,
  16. ],
  17. ];
  18.  
  19. $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
  20.  
  21. $serializer = new Serializer([$normalizer], [$encoder]);
  22.  
  23. $person = new Person();
  24. $person->setName('cordoval');
  25. $person->setAge(34);
  26. $person->setCreatedAt(new \DateTime('now'));
  27.  
  28. $serializer->serialize($person, 'json');
  29. // Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}

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

Normalizers

There are several types of normalizers available:

  • ObjectNormalizer
  • This normalizer leverages the PropertyAccess Componentto read and write in the object. It means that it can access to propertiesdirectly and through getters, setters, hassers, adders and removers. It supportscalling the constructor during the denormalization process.

Objects are normalized to a map of property names and values (names aregenerated removing the get, set, has, is or remove prefix fromthe method name and lowercasing the first letter; e.g. getFirstName() ->firstName).

The ObjectNormalizer is the most powerful normalizer. It is configured bydefault 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 callingthe constructor and the "setters" (public methods starting with "set").

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

  • PropertyNormalizer
  • This normalizer directly reads and writes public properties as well asprivate and protected properties (from both the class and all of itsparent classes). It supports calling the constructor during the denormalization process.

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

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

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

Unlike with json_encode circular references can be handled.

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

Encoders

Encoders turn arrays into formats and vice versa. They implementEncoderInterfacefor encoding (array to format) andDecoderInterface 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.  
  5. $encoders = [new XmlEncoder(), new JsonEncoder()];
  6. $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 theYaml Component.
  • CsvEncoder
  • This encoder encodes and decodes data in CSV.All these encoders are enabled by default when using the Serializer componentin a Symfony application.

The JsonEncoder

The JsonEncoder encodes to and decodes from JSON strings, based on the PHPjson_encode and json_decode functions.

The CsvEncoder

The CsvEncoder encodes to and decodes from CSV.

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

Deprecated since version 4.2: Relying on the default value false is deprecated since Symfony 4.2.

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"?>
  2. <response>
  3. <foo>1</foo>
  4. <foo>2</foo>
  5. <bar>1</bar>
  6. </response>

Be aware that this encoder will consider keys beginning with @ as attributes, and will usethe key #comment 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 resultsalways as a collection.

Tip

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

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

The YamlEncoder

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

Skipping null Values

By default, the Serializer will preserve properties containing a null value.You can change this behavior by setting the skip_null_values context optionto true:

  1. $dummy = new class {
  2. public $foo;
  3. public $bar = 'notNull';
  4. };
  5.  
  6. $normalizer = new ObjectNormalizer();
  7. $result = $normalizer->normalize($dummy, 'json', ['skip_null_values' => true]);
  8. // ['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.  
  6. public function setName($name)
  7. {
  8. $this->name = $name;
  9. }
  10.  
  11. public function getName()
  12. {
  13. return $this->name;
  14. }
  15.  
  16. public function setMembers(array $members)
  17. {
  18. $this->members = $members;
  19. }
  20.  
  21. public function getMembers()
  22. {
  23. return $this->members;
  24. }
  25. }
  26.  
  27. class Member
  28. {
  29. private $name;
  30. private $organization;
  31.  
  32. public function setName($name)
  33. {
  34. $this->name = $name;
  35. }
  36.  
  37. public function getName()
  38. {
  39. return $this->name;
  40. }
  41.  
  42. public function setOrganization(Organization $organization)
  43. {
  44. $this->organization = $organization;
  45. }
  46.  
  47. public function getOrganization()
  48. {
  49. return $this->organization;
  50. }
  51. }

To avoid infinite loops, GetSetMethodNormalizeror ObjectNormalizerthrow a CircularReferenceExceptionwhen such a case is encountered:

  1. $member = new Member();
  2. $member->setName('Kévin');
  3.  
  4. $organization = new Organization();
  5. $organization->setName('Les-Tilleuls.coop');
  6. $organization->setMembers([$member]);
  7.  
  8. $member->setOrganization($organization);
  9.  
  10. echo $serializer->serialize($organization, 'json'); // Throws a CircularReferenceException

The key circular_reference_limit in the default context sets the number oftimes it will serialize the same object before considering it a circularreference. The default value is 1.

Instead of throwing an exception, circular references can also be handledby custom callables. This is especially useful when serializing entitieshaving 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.  
  9. $serializer = new Serializer([$normalizer], [$encoder]);
  10. var_dump($serializer->serialize($org, 'json'));
  11. // {"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 circular_reference_handlerkey 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 datastructure:

  1. namespace Acme;
  2.  
  3. class MyObj
  4. {
  5. public $foo;
  6.  
  7. /**
  8. * @var self
  9. */
  10. public $child;
  11. }
  12.  
  13. $level1 = new MyObj();
  14. $level1->foo = 'level1';
  15.  
  16. $level2 = new MyObj();
  17. $level2->foo = 'level2';
  18. $level1->child = $level2;
  19.  
  20. $level3 = new MyObj();
  21. $level3->foo = 'level3';
  22. $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.  
  3. use Symfony\Component\Serializer\Annotation\MaxDepth;
  4.  
  5. class MyObj
  6. {
  7. /**
  8. * @MaxDepth(2)
  9. */
  10. public $child;
  11.  
  12. // ...
  13. }
  • YAML
  1. Acme\MyObj:
  2. attributes:
  3. child:
  4. max_depth: 2
  • XML
  1. <?xml version="1.0" ?>
  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 inorder to use this feature. It is done automatically when using the Serializer componentin a Symfony application. When using the standalone component, refer tothe groups documentation tolearn how to do that.

The check is only done if the enable_max_depth key of the serializer contextis set to true. In the following example, the third level is not serializedbecause it is deeper than the configured maximum depth of 2:

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

Deprecated since version 4.2: The setMaxDepthHandler()method is deprecated since Symfony 4.2. Use the max_depth_handlerkey 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.  
  3. $person1 = new Person();
  4. $person1->setName('foo');
  5. $person1->setAge(99);
  6. $person1->setSportsman(false);
  7.  
  8. $person2 = new Person();
  9. $person2->setName('bar');
  10. $person2->setAge(33);
  11. $person2->setSportsman(true);
  12.  
  13. $persons = [$person1, $person2];
  14. $data = $serializer->serialize($persons, 'json');
  15.  
  16. // $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 theArrayDenormalizerto the set of normalizers. By appending [] to the type parameter of thedeserialize() 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.  
  6. $serializer = new Serializer(
  7. [new GetSetMethodNormalizer(), new ArrayDenormalizer()],
  8. [new JsonEncoder()]
  9. );
  10.  
  11. $data = ...; // The serialized data from the previous example
  12. $persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');

The XmlEncoder

This encoder transforms arrays into XML and vice versa. For example, take anobject normalized as following:

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

The XmlEncoder encodes this object as follows:

<?xml version="1.0"?>
<response>
    <foo>1</foo>
    <foo>2</foo>
    <bar>1</bar>
</response>

The array keys beginning with @ are considered XML attributes:

['foo' => ['@bar' => 'value']];

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

Use the special # key to define the data of a node:

['foo' => ['@bar' => 'value', '#' => 'baz']];

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

Context

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

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

These are the options available:

  • xml_format_output
  • If set to true, formats the generated XML with line breaks and indentation.
  • xml_version
  • Sets the XML version attribute (default: 1.1).
  • xml_encoding
  • Sets the XML encoding attribute (default: utf-8).
  • xml_standalone
  • Adds standalone attribute in the generated XML (default: true).
  • xml_root_node_name
  • Sets the root node name (default: response).
  • remove_empty_tags
  • If set to true, removes all empty tags in the generated XML.

Handling Constructor Arguments

If the class constructor defines arguments, as usually happens withValue Objects, the serializer won't be able to create the object if somearguments are missing. In those cases, use the default_constructor_argumentscontext option:

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class MyObj
{
    private $foo;
    private $bar;

    public function __construct($foo, $bar)
    {
        $this->foo = $foo;
        $this->bar = $bar;
    }
}

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

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

Recursive Denormalization and Type Safety

The Serializer component can use the PropertyInfo Component to denormalizecomplex types (objects). The type of the class' property will be guessed using the providedextractor 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 4thparameter of the ObjectNormalizer:

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 $inner;
    private $date;

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

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

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

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

class ObjectInner
{
    public $foo;
    public $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 denormalizematches the type of the property (even for primitive types). For instance, if a string is provided, butthe type of the property is int, an UnexpectedValueExceptionwill be thrown. The type enforcement of the properties can be disabled by settingthe serializer context option ObjectNormalizer::DISABLE_TYPE_ENFORCEMENTto true.

Serializing Interfaces and Abstract Classes

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

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

The Serializer component provides an implementation of ClassDiscriminatorResolverInterfacecalled ClassDiscriminatorFromClassMetadatawhich uses the class metadata factory and a mapping configuration to serializeand deserialize objects of the correct class.

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

// ...
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 AnnotationLoader(new AnnotationReader()));

$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 thatdefines an abstract CodeRepository class extended by GitHubCodeRepositoryand BitBucketCodeRepository classes:

  • Annotations
namespace App;

use Symfony\Component\Serializer\Annotation\DiscriminatorMap;

/**
 * @DiscriminatorMap(typeProperty="type", mapping={
 *    "github"="App\GitHubCodeRepository",
 *    "bitbucket"="App\BitBucketCodeRepository"
 * })
 */
interface CodeRepository
{
    // ...
}
  • YAML
App\CodeRepository:
    discriminator_map:
        type_property: type
        mapping:
            github: 'App\GitHubCodeRepository'
            bitbucket: 'App\BitBucketCodeRepository'
  • XML
<?xml version="1.0" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
        https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
    <class name="App\CodeRepository">
        <discriminator-map type-property="type">
            <mapping type="github" class="App\GitHubCodeRepository"/>
            <mapping type="bitbucket" class="App\BitBucketCodeRepository"/>
        </discriminator-map>
    </class>
</serializer>

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

$serialized = $serializer->serialize(new GitHubCodeRepository());
// {"type": "github"}

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

Performance

To figure which normalizer (or denormalizer) must be used to handle an object,the Serializer class will call thesupportsNormalization()(or supportsDenormalization())of all registered normalizers (or denormalizers) in a loop.

The result of these methods can vary depending on the object to serialize, theformat and the context. That's why the result is not cached by default andcan result in a significant performance bottleneck.

However, most normalizers (and denormalizers) always return the same result whenthe object's type and the format are the same, so the result can be cached. Todo so, make those normalizers (and denormalizers) implement theCacheableSupportsMethodInterfaceand return true whenhasCacheableSupportsMethod()is called.

Note

All built-in normalizers and denormalizersas well the ones included in API Platform natively implement this interface.

Learn more

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.

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