Serialization API overview

Last updated on
4 November 2016

The Serialization API is new in Drupal 8. It is largely based on the Symfony Serializer component, so their documentation is also relevant.

For high-level information on what this module does, see the Serialization module documentation.

 Symfony documentation.

API features

Ordered by most to least frequently used APIs:

Serializing & deserializing
Using Drupal 8's serializer service's (\Symfony\Component\Serializer\SerializerInterface) serialize() and deserialize() methods:
$output = $this->serializer->serialize($entity, 'json');
$entity = $this->serializer->deserialize($output, \Drupal\node\Entity\Node::class, 'json');
Serialization format encoding/decoding (format → array → format
The encoder (\Symfony\Component\Serializer\Encoder\EncoderInterface) and decoder (\Symfony\Component\Serializer\Encoder\DecoderInterface, to add support for encoding to new serialization formats (i.e. for reading data) and decoding from them (i.e. for writing data).
Normalization (array → object → array)
The normalizer (\Symfony\Component\Serializer\Normalizer\NormalizerInterface) and denormalizer (\Symfony\Component\Serializer\Normalizer\DenormalizerInterface), to add support for normalizing to a new normalization format. The default format is as close to a 1:1 mapping of the object data as possible, but other formats may want to omit e.g. local IDs (for example node IDs are local, UUIDs are global) or add additional metadata (such as URIs linking to related data).
Entity resolvers
In a Drupal context, usually it will be (content) entities that end up being serialized. When given an entity to normalize (object → array) and then encode (array → format), that entity may have references to other entities. Those references may use either UUIDs (\Drupal\serialization\EntityResolver\UuidResolver) or local IDs (\Drupal\serialization\EntityResolver\TargetIdResolver). For advanced use cases, additional mechanisms for referring to other entities may exist; in that case, you would add an additional entity resolver.

See also