7

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?

2
  • Maybe $node->toArray() is what you're looking for? also you should return JsonResponse in this case.
    – user21641
    Feb 15, 2016 at 7:52
  • agree with @user21641 json return is better than using a serializer
    – stloc
    Dec 4, 2019 at 8:56

1 Answer 1

19

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']);
5
  • 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)." Dec 29, 2016 at 15:21
  • 5
    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) Dec 29, 2016 at 15:33
  • Thank you much for your answer, it helps a lot Mar 20, 2020 at 10:02
  • Don't forget to use use **return new Symfony\Component\HttpFoundation\JsonResponse($build); ** Jan 20, 2021 at 15:44
  • If you need to return this JSON directly from your controller use the following JSON response: return JsonResponse::fromJsonString($data); Mar 15, 2021 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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