Converting entity to JSON I am quite new to Drupal and Drupal 8. 

I have created a custom module that creates a custom content type. I am attempting to extract those entities and display them as JSON or XML. 

I have read through the Entities Api on loading, querying, and rendering entities but I am struggling to find view_mode_name types :

$build = $view_builder-&gt;view($entity, 'view_mode_name', $language-&gt;getId()); 


Would I be able to do something like : 

$build = $view_builder-&gt;view($entity, 'xml', $language-&gt;getId());


or does this only produce a 'render array' ? If this is the case then should I be looking at the Serializer Api ? If so would anyone be able to guide me in the right direction on using this ?

Here is my code so far : 

public function display() {
// use the debug component
Debug::enable();

// get node -&gt; testimonial content types
$entity_ids = \Drupal::entityQuery('node')
-&gt;condition('type', 'testimonial')
-&gt;execute(); // fetch

$node_storage = \Drupal::entityManager()-&gt;getStorage('node');

$data = $node_storage-&gt;loadMultiple($entity_ids);

$view_builder = \Drupal::entityManager()-&gt;getViewBuilder('node');

// render multiple 
return $view_builder-&gt;viewMultiple($data, 'xml');

}
View builders only display HTML/render arrays.

Look into the serialization/rest/hal modules if you want to extract the data of your entity, as you guessed already. 

Note that REST in core only supports content entities at the moment, but I assume you have one of those.

Also, I'd recommend hal+json serialization, provided by the hal.module instead of the raw json seralization, as that can't deal with things like references properly.