Matthew Downie
Matthew Downie

Reputation: 31

Drupal 8 Serialization and Deserialization

I am attempting to serialize a Node in Drupal 8. The serialization to JSON works and the output is readable and makes sense, but I am unable to deserialize it. Code is below:

    $entityManager = new EntityManager();
    $encoders = array(new JsonEncoder());
    $normalizers = array(
      new EntityNormalizer($entityManager),
      new TypedDataNormalizer($entityManager)
    );
    $serializer = new Serializer($normalizers, $encoders);
    $serialized_entity = $serializer->serialize($entity, 'json');
    $node = $serializer->deserialize($serialized_entity, '\Drupal\node\Entity\Node', 'json');

The truncated error is below:

    Error: Call to a member function get() on null in Drupal\Core\Entity\EntityManager->getEntityTypeFromClass() (line 377 of /vagrant/drupal-8.2.1/core/lib/Drupal/Core/Entity/EntityManager.php) #0 /vagrant/drupal-8.2.1/core/modules/serialization/src/Normalizer/EntityNormalizer.php(43): Drupal\Core\Entity\EntityManager->getEntityTypeFromClass('\\Drupal\\node\\En...') #1

A little background, I am trying to use this in an insert hook to serialize the node and send it to an endpoint, where I want to deserialize it. Any help is greatly appreciated. Thanks.

Upvotes: 1

Views: 2129

Answers (1)

Yonas Sahlemariam
Yonas Sahlemariam

Reputation: 11

Look at serialization.services.yml. There are already defined normalizers and encoders for content entities. Just do the following:

\Drupal::service('serializer')->serialize($node, 'json');

Upvotes: 1

Related Questions