Skip to content

Instantly share code, notes, and snippets.

@DavMorr
Last active June 4, 2024 22:10
Show Gist options
  • Save DavMorr/3d3275f695b9900f8ea75bb302428eec to your computer and use it in GitHub Desktop.
Save DavMorr/3d3275f695b9900f8ea75bb302428eec to your computer and use it in GitHub Desktop.
Drupal 8 : serialize typed data into JSON - Among other rad things that you can do via the type data api in drupal 8. the following example shows how to interact with typed data with the core Serialize service for serializing and deserializing lists of URI data types items.

Drupal 8 : serialize typed data into JSON

from: Typed Data API overview (drupal.org)

  // Serialize Typed Data into JSON.
  $listDefinition = \Drupal::typedDataManager()->createListDataDefinition('uri');
  $list = \Drupal::typedDataManager()->create($listDefinition, ['http://example.com', 'http://drupal.org']);
  $serializer = \Drupal::service('serializer');
  echo $serializer->serialize($list, 'json');
  // ["http://example.com", "http://drupal.org"]

  // Deserialize JSON into Typed Data.
  $encoded = json_encode(["http://example.com", "http://drupal.org"]);
  $myList = $serializer->deserialize($encoded, 'Drupal\Core\TypedData\Plugin\DataType\Uri', 'json', ['plugin_id' => 'uri']);
  echo $myList->get(0)->getValue();
  // 'http://example.com'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment