The Serializer Component
Edit this pageWarning: You are browsing the documentation for Symfony 2.6, which is no longer maintained.
Read the updated version of this page for Symfony 6.1 (the current stable version).
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 simple schema.

As you can see in the picture above, an array is used as a man in the middle. 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 complicated topic, and while this component may not work in all cases, it can be a useful tool while developing tools to serialize and deserialize your objects.
Installation
You can install the component in 2 different ways:
- Install it via Composer (
symfony/serializer
on Packagist); - Use the official Git repository (https://github.com/symfony/Serializer).
Then, require the vendor/autoload.php
file to enable the autoloading mechanism
provided by Composer. Otherwise, your application won't be able to find the classes
of this Symfony component.
Usage
Using the Serializer component is really simple. You just need to 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\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
There are several normalizers available, e.g. the
GetSetMethodNormalizer or
the PropertyNormalizer.
To read more about them, refer to the Normalizers section of this page. All
the examples shown below use the GetSetMethodNormalizer
.
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
namespace Acme;
class Person
{
private $age;
private $name;
private $sportsman;
// Getters
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
// Issers
public function isSportsman()
{
return $this->sportsman;
}
// Setters
public function setName($name)
{
$this->name = $name;
}
public function setAge($age)
{
$this->age = $age;
}
public function setSportsman($sportsman)
{
$this->sportsman = $sportsman;
}
}
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
$person = new Acme\Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsman(false);
$jsonContent = $serializer->serialize($person, 'json');
// $jsonContent contains {"name":"foo","age":99,"sportsman":false}
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.
Ignoring Attributes when Serializing
2.3
The GetSetMethodNormalizer::setIgnoredAttributes method was introduced in Symfony 2.3.
As an option, there's a way to ignore attributes from the origin object when serializing. To remove those attributes use the setIgnoredAttributes() method on the normalizer definition:
1 2 3 4 5 6 7 8 9 10
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
$normalizer = new GetSetMethodNormalizer();
$normalizer->setIgnoredAttributes(array('age'));
$encoder = new JsonEncoder();
$serializer = new Serializer(array($normalizer), array($encoder));
$serializer->serialize($person, 'json'); // Output: {"name":"foo","sportsman":false}
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
$data = <<<EOF
<person>
<name>foo</name>
<age>99</age>
<sportsman>false</sportsman>
</person>
EOF;
$person = $serializer->deserialize($data, 'Acme\Person', '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 array
Using Camelized Method Names for Underscored Attributes
2.3
The GetSetMethodNormalizer::setCamelizedAttributes method was introduced in Symfony 2.3.
Sometimes property names from the serialized content are underscored (e.g.
first_name
). Normally, these attributes will use get/set methods like
getFirst_name
, when getFirstName
method is what you really want. To
change that behavior use the
setCamelizedAttributes()
method on the normalizer definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();
$normalizer->setCamelizedAttributes(array('first_name'));
$serializer = new Serializer(array($normalizer), array($encoder));
$json = <<<EOT
{
"name": "foo",
"age": "19",
"first_name": "bar"
}
EOT;
$person = $serializer->deserialize($json, 'Acme\Person', 'json');
As a final result, the deserializer uses the first_name
attribute as if
it were firstName
and uses the getFirstName
and setFirstName
methods.
Serializing Boolean Attributes
2.5
Support for is*
accessors in
GetSetMethodNormalizer
was introduced in Symfony 2.5.
If you are using isser methods (methods prefixed by is
, like
Acme\Person::isSportsman()
), the Serializer component will automatically
detect and use it to serialize related attributes.
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
use Acme\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($dateTime) {
return $dateTime instanceof \DateTime
? $dateTime->format(\DateTime::ISO8601)
: '';
};
$normalizer->setCallbacks(array('createdAt' => $callback));
$serializer = new Serializer(array($normalizer), array($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
There are several types of normalizers available:
- 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 serialized to a map of property names (method name stripped of the "get" prefix and converted to lower case) to property values.
- PropertyNormalizer
- This normalizer directly reads and writes public properties as well as private and protected properties. Objects are normalized to a map of property names to property values.
- .. versionadded:: 2.6 The
- PropertyNormalizer class was introduced in Symfony 2.6.
Handling Circular References
2.6
Handling of circular references was introduced in Symfony 2.6. In previous versions of Symfony, circular references led to infinite loops.
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 $name;
private $members;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setMembers(array $members)
{
$this->members = $members;
}
public function getMembers()
{
return $this->members;
}
}
class Member
{
private $name;
private $organization;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setOrganization(Organization $organization)
{
$this->organization = $organization;
}
public function getOrganization()
{
return $this->organization;
}
}
To avoid infinite loops, GetSetMethodNormalizer throws 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');
$org = new Organization();
$org->setName('Les-Tilleuls.coop');
$org->setMembers(array($member));
$member->setOrganization($org);
echo $serializer->serialize($org, 'json'); // Throws a CircularReferenceException
The setCircularReferenceLimit()
method of this normalizer sets the number
of times it will serialize the same object before considering it a circular
reference. Its 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
$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getName();
});
$serializer = new Serializer(array($normalizer), array($encoder));
var_dump($serializer->serialize($org, 'json'));
// {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}
JMSSerializer
A popular third-party library, JMS serializer, provides a more sophisticated albeit more complex solution. This library includes the ability to configure how your objects should be serialized/deserialized via annotations (as well as YAML, XML and PHP), integration with the Doctrine ORM, and handling of other complex cases.