I am trying to create my own Node Entity Normalizer in Drupal 10 to get rid of the unnecessary JSON structure that comes out of the box. For example, instead of my API's returning
{
"nid": [
{
"value": 7
}
]
}
I want to make it return
{
"nid": 7
}
So I've tried the following options in my custom module:
- Typed Data Interface
example_normalizer.services.yml
services:
example_normalizer.typed_data:
class: Drupal\example_normalizer\Normalizer\CustomTypedDataNormalizer
tags:
- { name: normalizer, priority: 2 }
src/Normalizer/CustomTypedDataNormalizer.php
<?php
namespace Drupal\example_normalizer\Normalizer;
use Drupal\serialization\Normalizer\NormalizerBase;
/**
* Converts typed data objects to arrays.
*/
class CustomTypedDataNormalizer extends NormalizerBase {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = 'Drupal\Core\TypedData\TypedDataInterface';
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = array()) {
$value = $object->getValue();
if (isset($value[0]) && isset($value[0]['value'])) {
$value = $value[0]['value'];
}
return $value;
}
}
and
- Custom Node Entity Normalizer
example_normalizer.services.yml
services:
example_normalizer.node_entity:
class: Drupal\example_normalizer\Normalizer\NodeEntityNormalizer
arguments: ['@entity.manager']
tags:
- { name: normalizer, priority: 8 }
src/Normalizer/NodeEntityNormalizer.php
<?php
namespace Drupal\example_normalizer\Normalizer;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\Core\Datetime\DrupalDateTime;
/**
* Converts the Drupal entity object structures to a normalized array.
*/
class NodeEntityNormalizer extends ContentEntityNormalizer {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = 'Drupal\node\NodeInterface';
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = array()) {
// Similar logic as above
}
}
However, in both cases, when I clear the cache I am getting the error
PHP Fatal error: Uncaught Error: Class "Drupal\example_normalizer\Normalizer\NodeEntityNormalizer" not found in /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php:262
What am I missing in my module that this is not getting picked up?
I'd like to be able to make a call like
$serializer = \Drupal::service('serializer')
$custom_json = $serializer->serialize($entity, 'json', ['plugin_id' => 'my_custom_normalizer']