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.
$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.
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