### Install JMSSerializerBundle with Composer Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/installation.rst Use Composer to download the latest stable version of the JMSSerializerBundle. This requires a global Composer installation. ```bash $ composer require jms/serializer-bundle ``` -------------------------------- ### Install JMS Serializer Bundle Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Install the bundle using Composer and register it in your Symfony application's bundles configuration. ```bash composer require jms/serializer-bundle ``` ```php // config/bundles.php return [ // ... JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true], ]; ``` -------------------------------- ### Serializer Configuration - YAML Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Example of a comprehensive YAML configuration for JMSSerializerBundle. It covers profiler, enum support, default value property reader support, Twig integration, custom handlers, object constructors, property naming, metadata loading, and default context settings. ```yaml jms_serializer: profiler: %kernel.debug% enum_support: true # PHP 8.1 Enums support, false by default for backward compatibility default_value_property_reader_support: true # PHP 8.0 Constructor Promotion default value support, false by default for backward compatibility twig_enabled: 'default' # on which instance is twig enabled handlers: datetime: default_format: "Y-m-d\TH:i:sP" # ATOM default_deserialization_formats: - "Y-m-d\TH:i:sP" # ATOM default_timezone: "UTC" # defaults to whatever timezone set in php.ini or via date_default_timezone_set array_collection: initialize_excluded: false symfony_uid: default_format: "canonical" cdata: true subscribers: doctrine_proxy: initialize_virtual_types: false initialize_excluded: false object_constructors: doctrine: enabled: true fallback_strategy: "null" # possible values ("null" | "exception" | "fallback") property_naming: id: ~ separator: _ lower_case: true metadata: cache: file debug: "%kernel.debug%" file_cache: dir: "%kernel.cache_dir%/serializer" include_interfaces: false infer_types_from_doc_block: false infer_types_from_doctrine_metadata: true # Using auto-detection, the mapping files for each bundle will be # expected in the Resources/config/serializer directory. # # Example: # class: My\FooBundle\Entity\User # expected path: @MyFooBundle/Resources/config/serializer/Entity.User.(yml|xml|php) auto_detection: true # if you don't want to use auto-detection, you can also define the # namespace prefix and the corresponding directory explicitly directories: any-name: namespace_prefix: "My\FooBundle" path: "@MyFooBundle/Resources/config/serializer" another-name: namespace_prefix: "My\BarBundle" path: "@MyBarBundle/Resources/config/serializer" warmup: # list of directories to scan searching for php classes to use when warming up the cache paths: included: [] excluded: [] expression_evaluator: id: jms_serializer.expression_evaluator # auto detected default_context: serialization: serialize_null: false version: ~ attributes: {} groups: ['Default'] enable_max_depth_checks: false ``` -------------------------------- ### Add JMSSerializerBundle to AppKernel Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/index.rst Register the JMSSerializerBundle in your AppKernel.php file after installation. ```php // in AppKernel::registerBundles() $bundles = array( // ... new JMS\SerializerBundle\JMSSerializerBundle(), // ... ); ``` -------------------------------- ### Define Custom Expression Function Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Implement ExpressionFunctionProviderInterface to add custom functions to the expression evaluator. The str_rot13 example shows how to define both compile-time and runtime logic for a function. ```php use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; class MyFunctionProvider implements ExpressionFunctionProviderInterface { public function getFunctions(): array { return [ new ExpressionFunction( 'str_rot13', fn($arg) => sprintf('str_rot13(%s)', $arg), fn(array $variables, $value) => str_rot13($value) ), ]; } } ``` -------------------------------- ### Register Custom Expression Function Provider Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Extend the Expression Language with custom functions for use in annotations like @Exclude(if=...). Ensure the symfony/expression-language component is installed. ```yaml services: App\MyFunctionProvider: tags: - { name: jms.expression.function_provider } ``` -------------------------------- ### Define Metadata Directories (YAML) Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Configure metadata directories for serialization using YAML, specifying namespace prefixes and paths. ```yaml jms_serializer: metadata: directories: App: namespace_prefix: "App\Entity" path: "%kernel.project_dir%/serializer/app" FOSUB: namespace_prefix: "FOS\UserBundle" path: "%kernel.project_dir%/serializer/FOSUB" ``` -------------------------------- ### Configure JSON and XML Visitor Options Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Globally configure options for JSON serialization/deserialization and XML serialization. This includes setting JSON pretty printing, depth, strictness, and XML formatting, version, encoding, and default root element. ```yaml # config/packages/jms_serializer.yaml jms_serializer: visitors: json_serialization: options: !php/const JSON_PRETTY_PRINT # or integer bitmask: 128 depth: 512 json_deserialization: options: 0 strict: true # throw on type mismatch xml_serialization: format_output: true version: "1.0" encoding: "UTF-8" default_root_name: "result" default_root_ns: ~ xml_deserialization: external_entities: false doctype_whitelist: - '' ``` -------------------------------- ### Define Metadata Directories (XML) Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Configure metadata directories for serialization using XML, specifying namespace prefixes and paths. ```xml ``` -------------------------------- ### Configure Metadata Caching and Warmup Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Configure file-based metadata caching and enable automatic detection and type inference from doc blocks and Doctrine metadata. The cache directory can be specified, and warmup paths can be included or excluded. ```yaml # config/packages/jms_serializer.yaml jms_serializer: metadata: cache: file debug: '%kernel.debug%' file_cache: dir: '%kernel.cache_dir%/serializer' auto_detection: true infer_types_from_doc_block: true infer_types_from_doctrine_metadata: true include_interfaces: false warmup: paths: included: - '%kernel.project_dir%/src/Entity' - '%kernel.project_dir%/src/DTO' excluded: - '%kernel.project_dir%/src/Entity/Internal' ``` -------------------------------- ### Configure Serialization Context (Groups and Versioning) Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Control serialization and deserialization at runtime using `SerializationContext` and `DeserializationContext`. Set active groups, version, and null handling. ```php use JMS\Serializer\SerializationContext; use JMS\Serializer\DeserializationContext; // Serialize with a specific group $context = SerializationContext::create() ->setGroups(['public']) ->setVersion('1.5') ->setSerializeNull(true); $json = $serializer->serialize($user, 'json', $context); // Only properties in group 'public' that exist since <= 1.5 are serialized // Deserialize with context $context = DeserializationContext::create()->setVersion('2.0'); $user = $serializer->deserialize($json, User::class, 'json', $context); ``` -------------------------------- ### Warm up Serializer Metadata Cache Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Execute the Symfony console command to warm up the serializer metadata cache. This pre-generates metadata files to improve performance. ```bash # Warm up the serializer metadata cache php bin/console cache:warmup ``` -------------------------------- ### Register a Handler Service (XML) Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Register a service as a handler for a specific type, direction, and format using XML configuration. ```xml ``` -------------------------------- ### Register a Handler Service (YAML) Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Register a service as a handler for a specific type, direction, and format using YAML configuration. ```yaml my_handler: class: MyHandler tags: - name: jms_serializer.handler type: DateTime direction: serialization format: json method: serializeDateTimeToJson ``` -------------------------------- ### Configure Multiple Serializer Instances Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Define independent serializer instances with distinct configurations, such as different property naming strategies, by specifying them under the 'instances' key in the serializer configuration. ```yaml # config/packages/jms_serializer.yaml jms_serializer: instances: snake_case: property_naming: separator: "_" lower_case: true camel_case: property_naming: separator: "" lower_case: false ``` -------------------------------- ### Configure Property Naming Strategy Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Control how PHP property names are transformed into serialized key names. Supports custom separators and lowercasing. ```yaml jms_serializer: property_naming: id: ~ separator: "_" lower_case: true ``` -------------------------------- ### Define Metadata with YAML Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Configure serialization rules for classes using YAML files, useful for classes you cannot modify directly. Specify exclusion policy, properties, exposure, type, and groups. ```yaml # config/serializer/app/Entity.User.yml App\Entity\User: exclusion_policy: ALL properties: id: expose: true type: integer groups: [public, admin] name: expose: true serialized_name: full_name type: string groups: [public] email: expose: true type: string groups: [admin] ``` ```yaml # config/packages/jms_serializer.yaml jms_serializer: metadata: directories: App: namespace_prefix: "App\Entity" path: "%kernel.project_dir%/config/serializer/app" ``` -------------------------------- ### Enable Doctrine Object Constructor Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Configure JMS Serializer to use Doctrine's object constructor for deserialization, allowing it to load existing entities from the database instead of creating new instances. This requires setting 'enabled: true' and optionally configuring a fallback strategy. ```yaml # config/packages/jms_serializer.yaml jms_serializer: object_constructors: doctrine: enabled: true fallback_strategy: "fallback" # "null" | "exception" | "fallback" ``` -------------------------------- ### Register an Expression Function Provider (YAML) Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Register a custom expression function provider using YAML configuration. ```yaml my_function_provider: class: MyFunctionProvider tags: - jms.expression.function_provider ``` -------------------------------- ### User Serialization Configuration Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Configure serialization for the FOSUserBundle User model, specifying which properties to expose and their types. ```yaml FOS\UserBundle\Model\User: exclusion_policy: ALL properties: id: expose: true type: integer username: expose: true type: string email: expose: true type: string groups: [admin] ``` -------------------------------- ### Generate Changelog with Github Changelog Generator Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/META.md Use this command to generate a changelog for the JMSSerializerBundle. Ensure you replace GITHUB-TOKEN with your actual token. ```bash github_changelog_generator --user=schmittjoh --project=JMSSerializerBundle --pull-requests --no-compare-link --future-release=RELEASE_NR -t GITHUB-TOKEN ``` -------------------------------- ### Enable JMSSerializerBundle in Symfony Standard Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/installation.rst For Symfony Standard applications, enable the bundle by adding it to the app/AppKernel.php file within the registerBundles method. ```php ``` -------------------------------- ### Serialize and Deserialize Data with JMSSerializer Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/index.rst Obtain the 'jms_serializer' service and use its serialize and deserialize methods. The service ID can also be 'jms_serializer.instances.default'. ```php $serializer = $container->get('jms_serializer'); $serializer->serialize($data, $format); $data = $serializer->deserialize($inputStr, $typeName, $format); ``` -------------------------------- ### Enable Symfony Profiler Integration Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Enable the JMSSerializerBundle panel in the Symfony Web Profiler when kernel.debug is enabled for introspection of serialization runs. ```yaml jms_serializer: profiler: '%kernel.debug%' ``` -------------------------------- ### Set Doctrine Object Constructor as Default Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Alias the default 'jms_serializer.object_constructor' service to 'jms_serializer.doctrine_object_constructor' in your services.yaml to make it the active constructor. ```yaml # config/services.yaml — set as the default constructor services: jms_serializer.object_constructor: alias: jms_serializer.doctrine_object_constructor public: false ``` -------------------------------- ### Update Naming Strategy Configuration Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/UPGRADING.md Modify the configuration to define the property naming strategy using service IDs instead of class names. ```yaml parameters: jms_serializer.serialized_name_annotation_strategy.class: JMS\Serializer\Naming\IdenticalPropertyNamingStrategy ``` ```yaml jms_serializer: property_naming: id: 'jms_serializer.identical_property_naming_strategy' # service id of the naming strategy ``` -------------------------------- ### Inject or Fetch Named Serializer Instances Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Inject a default serializer instance via constructor or retrieve specific named instances (e.g., 'snake_case', 'camel_case') from the service container. ```php // Inject a specific instance by its service ID use JMS\Serializer\SerializerInterface; class ApiController { public function __construct( // Default instance private SerializerInterface $serializer, ) {} } // Or fetch a named instance from the container $snakeCaseSerializer = $container->get('jms_serializer.instances.snake_case'); $camelCaseSerializer = $container->get('jms_serializer.instances.camel_case'); ``` -------------------------------- ### Basic Serialization and Deserialization with SerializerInterface Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Use the `jms_serializer` service to serialize PHP objects to JSON or XML, and deserialize them back. Supports deserializing lists of objects. ```php use App\Entity\User; use JMS\Serializer\SerializerInterface; class UserController { public function __construct(private SerializerInterface $serializer) {} public function export(User $user): string { // Serialize object to JSON $json = $this->serializer->serialize($user, 'json'); // {"id":1,"name":"Alice","email":"alice@example.com"} // Serialize to XML $xml = $this->serializer->serialize($user, 'xml'); // Deserialize back from JSON $restoredUser = $this->serializer->deserialize($json, User::class, 'json'); // Deserialize a list $users = $this->serializer->deserialize($json, 'array<' . User::class . '>', 'json'); return $json; } } ``` -------------------------------- ### Default JMS Serializer Context Configuration Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Sets default serialization and deserialization contexts, including null handling, versioning, groups, and max depth checks. ```yaml jms_serializer: default_context: serialization: serialize_null: false version: ~ groups: ['Default'] enable_max_depth_checks: false attributes: {} deserialization: serialize_null: false version: ~ groups: ['Default'] ``` -------------------------------- ### Define Metadata with PHP Attributes Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Control serialization behavior using PHP 8 attributes on entity properties. Configure exposure, type, groups, serialized names, and version constraints. ```php use JMS\Serializer\Annotation as JMS; #[JMS\ExclusionPolicy('all')] class User { #[JMS\Expose] #[JMS\Type('integer')] #[JMS\Groups(['public', 'admin'])] private int $id; #[JMS\Expose] #[JMS\SerializedName('full_name')] #[JMS\Type('string')] #[JMS\Since('1.0')] #[JMS\Until('2.0')] private string $name; #[JMS\Expose] #[JMS\Type('string')] #[JMS\Groups(['admin'])] private string $email; // password is NOT exposed (ExclusionPolicy = 'all') private string $password; } // Result (group 'public', version 1.0): // {"id": 1, "full_name": "Alice"} // Result (group 'admin'): // {"id": 1, "full_name": "Alice", "email": "alice@example.com"} ``` -------------------------------- ### Custom Expression Function Provider Implementation Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Implement the ExpressionFunctionProviderInterface to add custom functions to the Expression Language. ```php use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; class MyFunctionProvider implements ExpressionFunctionProviderInterface { public function getFunctions() { return [ new ExpressionFunction('str_rot13', function ($arg) { return sprintf('str_rot13(%s)', $arg); }, function (array $variables, $value) { return str_rot13($value); }) ]; } } ``` -------------------------------- ### User Serialization Event Subscriber Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Implements EventSubscriberInterface to hook into pre-serialization and post-serialization events for the User class in JSON format. ```php use JMS\Serializer\EventDispatcher\EventSubscriberInterface; use JMS\Serializer\EventDispatcher\PreSerializeEvent; use JMS\Serializer\EventDispatcher\ObjectEvent; use JMS\Serializer\GenericSerializationVisitor; class UserSerializationSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ [ 'event' => 'serializer.pre_serialize', 'class' => 'App\Entity\User', 'format' => 'json', 'method' => 'onPreSerialize', ], [ 'event' => 'serializer.post_serialize', 'class' => 'App\Entity\User', 'format' => 'json', 'method' => 'onPostSerialize', ], ]; } public function onPreSerialize(PreSerializeEvent $event): void { /** @var User $user */ $user = $event->getObject(); // Manipulate object before serialization } public function onPostSerialize(ObjectEvent $event): void { /** @var GenericSerializationVisitor $visitor */ $visitor = $event->getVisitor(); // Inject additional data into the output $visitor->visitProperty( new \JMS\Serializer\Metadata\StaticPropertyMetadata('', 'computed_field', null), 'dynamic_value' ); } } ``` ```yaml # config/services.yaml (or use autoconfiguration) services: App\Serializer\UserSerializationSubscriber: tags: - { name: jms_serializer.event_subscriber } ``` -------------------------------- ### Register Custom Money Handler with SubscribingHandlerInterface Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Implements SubscribingHandlerInterface to automatically register custom serialization and deserialization logic for the Money type. ```php use JMS\Serializer\Handler\SubscribingHandlerInterface; use JMS\Serializer\GraphNavigatorInterface; use JMS\Serializer\JsonSerializationVisitor; use JMS\Serializer\JsonDeserializationVisitor; use JMS\Serializer\Context; use Money\Money; use Money\Currency; class MoneyHandler implements SubscribingHandlerInterface { public static function getSubscribingMethods(): array { return [ [ 'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION, 'format' => 'json', 'type' => Money::class, 'method' => 'serializeMoneyToJson', ], [ 'direction' => GraphNavigatorInterface::DIRECTION_DESERIALIZATION, 'format' => 'json', 'type' => Money::class, 'method' => 'deserializeMoneyFromJson', ], ]; } public function serializeMoneyToJson(JsonSerializationVisitor $visitor, Money $money, array $type, Context $context): array { return ['amount' => $money->getAmount(), 'currency' => $money->getCurrency()->getCode()]; } public function deserializeMoneyFromJson(JsonDeserializationVisitor $visitor, $data, array $type, Context $context): Money { return new Money($data['amount'], new Currency($data['currency'])); } } ``` ```yaml # config/services.yaml services: App\Serializer\MoneyHandler: tags: - { name: jms_serializer.subscribing_handler } ``` -------------------------------- ### Enable JMSSerializerBundle in Symfony Flex Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/installation.rst For Symfony Flex applications, the bundle is usually enabled automatically. If not, add it to your config/bundles.php file. ```php ['all' => true], ]; ``` -------------------------------- ### Configure built-in datetime handler Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/UPGRADING.md Configure the default format and timezone for the built-in datetime handler in JMS serializer. ```yaml jms_serializer: handlers: datetime: default_format: DateTime::ISO8601 default_timezone: UTC ``` -------------------------------- ### Configure Doctrine Object Constructor - YAML Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Override the default object constructor service alias to use the Doctrine object constructor. This is useful when working with Doctrine entities during deserialization. ```yaml services: jms_serializer.object_constructor: alias: jms_serializer.doctrine_object_constructor public: false ``` -------------------------------- ### Use JMSSerializer in Templates Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/index.rst Utilize the 'jms_serialize' filter within templates to serialize data to JSON or XML. ```html+jinja {{ data | jms_serialize }} {# serializes to JSON #} {{ data | jms_serialize('json') }} {{ data | jms_serialize('xml') }} ``` -------------------------------- ### Configure Doctrine Object Constructor - XML Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/Resources/doc/configuration.rst Override the default object constructor service alias to use the Doctrine object constructor using XML configuration. This is useful when working with Doctrine entities during deserialization. ```xml ``` -------------------------------- ### Enable Twig Serialization Filter Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Configure JMSSerializerBundle to enable the Twig filter for serialization. ```yaml jms_serializer: twig_enabled: 'default' ``` -------------------------------- ### Deserialize with Doctrine Object Constructor Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt When deserializing JSON data into a Doctrine entity, JMS will now use the configured object constructor to find and update the existing entity in the database based on the provided ID. ```php // During deserialization, JMS will call EntityManager::find() to load existing entity $json = '{"id": 42, "name": "Updated Name"}'; $user = $serializer->deserialize($json, User::class, 'json'); // $user is the managed Doctrine entity with id=42, with 'name' updated ``` -------------------------------- ### Specify DateTime format with @Type annotation Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/UPGRADING.md Specify the format and timezone for a DateTime property directly using the @Type annotation. ```php /** @Type("DateTime<'Y-m-d', 'UTC'>") */ private $createdAt; ``` -------------------------------- ### Rename Twig Filter from serialize to jms_serialize Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/UPGRADING.md Update Twig templates to use the new `jms_serialize` filter instead of the deprecated `serialize` filter. ```jinja {{ data | serialize }} ``` ```jinja {{ data | jms_serialize }} ``` -------------------------------- ### Override Property Naming with SerializedName Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Use the @SerializedName annotation to override the default property naming strategy on a per-property basis. ```php // With separator: "_" and lower_case: true (default): // PHP property: $firstName → serialized key: "first_name" // PHP property: $createdAt → serialized key: "created_at" // Override per-property with @SerializedName: use JMS\Serializer\Annotation as JMS; class Product { #[JMS\SerializedName('product_title')] private string $title; } ``` -------------------------------- ### Dynamic Property Exclusion with Expression Language Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Uses JMS annotations with Symfony Expression Language to conditionally expose properties based on runtime conditions like user roles or container parameters. ```php use JMS\Serializer\Annotation as JMS; class User { #[JMS\Expose] private string $name; // Only expose 'email' if the current user has ROLE_ADMIN #[JMS\Expose] #[JMS\Exclude(if: "!is_granted('ROLE_ADMIN')")] private string $email; // Only expose if a container parameter is true #[JMS\Expose] #[JMS\Exclude(if: "!parameter('expose_internal_id')")] private int $internalId; } ``` -------------------------------- ### Register Custom Handler with jms_serializer.handler Tag Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Explicitly registers a custom handler service using the 'jms_serializer.handler' tag with specific type, direction, format, and method configurations. ```yaml services: App\Serializer\DateTimeHandler: tags: - name: jms_serializer.handler type: DateTime direction: serialization format: json method: serializeDateTimeToJson ``` -------------------------------- ### Override Third-Party Metadata Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Configure JMS Serializer to use custom metadata for classes from external bundles by specifying a namespace prefix and a local path for the metadata files. ```yaml # config/packages/jms_serializer.yaml jms_serializer: metadata: directories: FOSUser: namespace_prefix: "FOS\\UserBundle\\Model" path: "%kernel.project_dir%/config/serializer/fosuser" ``` -------------------------------- ### Twig Integration for Serialization Source: https://context7.com/schmittjoh/jmsserializerbundle/llms.txt Use the jms_serialize Twig filter to serialize objects directly within Twig templates. Supports default JSON and specific formats like XML. ```twig {# Serialize to JSON (default) #} {{ user | jms_serialize }} ``` ```twig {# Serialize to a specific format #} {{ user | jms_serialize('json') }} {{ user | jms_serialize('xml') }} ``` ```twig {# In a Twig template rendering a JSON response inline #} ``` -------------------------------- ### Force Serialization Type to Array for Traversable Objects Source: https://github.com/schmittjoh/jmsserializerbundle/blob/master/UPGRADING.md When objects implementing Traversable are no longer serialized as expected, use the `@Type("array")` annotation to restore previous behavior. ```php /** @Type("array") */ private $myTraversableObject; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.