Community Documentation

Serialization API in Drupal 8

Last updated March 9, 2013. Created by linclark on January 25, 2013.
Edited by podarok. Log in to edit this page.

Drupal 8 can output JSON and XML versions of data using the Serialization API. Modules can add new serialization formats, as core's HAL (#1924854: [META] Hypermedia Application Language (HAL) support) module will.

Serializing data

To serialize data, get the serializer from the container.

$serializer = $this->container->get('serializer');

Pass a content entity to the serializer and pass the short name of the format (e.g. 'json' or 'xml').

$output = $serializer->serialize($entity, 'json');

In core, only content entities (node, user, etc) are supported. However, it is easy to add support for other classes.

NOTE: Until core entity types are transitioned to EntityNG, only the EntityTest entity supports serialization.

Deserializing data

Get the serializer from the container, as shown above.

Pass data into the serializer, as well as target entity class (with PSR-0 namespace), and the short name of the format (e.g. 'json' or 'xml').

$entity = $serializer->deserialize($incoming_data, 'Drupal\entity_test\Plugin\Core\Entity\EntityTest', 'json');

To be completed:

  • Adding support for other classes
  • Adding support for other formats

Comments

Pass an entity, a node, user or comment to serialize()

When i try to pass an entity - node, user or comment - loading by:

$entity = load_node(1);
$entity = load_user(1);
$entity = load_comment(1);

to serialize($entity,'json')

an error message occured, about object must be traversable e.g.

Exception: Objects returned by Drupal\comment\Plugin\Core\Entity\Comment::getIterator() must be traversable or implement interface Iterator in Drupal\Core\Serialization\ComplexDataNormalizer::normalize()

How to load correctly an entity?

OK, it is not working this way right now. Just works for EntityNG which is under constr.

nobody click here