5

I am trying to use \Drupal\node\Entity\Node::load($nid) to store a node object in a variable and pass the variable into drupal 8's serialization component or even symphony's serialization methods. All my efforts have resulted in a JSON object that is only encoding the first property of the node which is {"in_preview":null}.

For example the following callback returns {"in_preview":null}

public function page(){

  $nrm = new \Drupal\Component\Serialization\Json;
  $node = Node::load(2);
  $json = $nrm -> encode($node, 'json');

  return $json;

}

What class/method would accomplish serialization of $node in the above code?

  • Maybe $node->toArray() is what you're looking for? also you should return JsonResponse in this case. – user21641 Feb 15 '16 at 7:52
9

You should use the serializer service if you want to serialize a Drupal data type (Typed Data API) so that normalization is run properly. This requires enabling the serialization module as pointed out by Alari Truuts, which defines the serializer service.

The serialize method is a little confusing as to what the $context parameter means. For Drupal Typed Data, it requires the plugin id of the data type (EntityAdapter in this case).

$serializer = \Drupal::service('serializer');
$node = Node::load(2);
$data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);
  • 2
    When trying to use the serializer as a service I get the following error: "Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "serializer". in Drupal\Component\DependencyInjection\Container->get() (line 157 of core/lib/Drupal/Component/DependencyInjection/Container.php)." – Alari Truuts Dec 29 '16 at 15:21
  • 4
    Apparently it makes sense to first enable the serialization module where the service and classes are in :) (Leaving this here in case someone else stumples upon this) – Alari Truuts Dec 29 '16 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.