Last updated December 30, 2013. Created by linclark on January 25, 2013.
Edited by yched, Gábor Hojtsy, 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] Hypertext 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.

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

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.