single: Serializer
Symfony provides a serializer to serialize/deserialize to and from objects and different formats (e.g. JSON or XML). Before using it, read the Serializer component docs </components/serializer>
to get familiar with its philosophy and the normalizers and encoders terminology.
In applications using Symfony Flex <symfony-flex>
, run this command to install the serializer
Symfony pack <symfony-packs>
before using it:
$ composer require symfony/serializer-pack
Once enabled, the serializer service can be injected in any service where you need it or it can be used in a controller:
// src/Controller/DefaultController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Serializer\SerializerInterface;
class DefaultController extends AbstractController
{
public function index(SerializerInterface $serializer)
{
// keep reading for usage examples
}
}
Once enabled, the serializer
service will be available in the container. It comes with a set of useful encoders <component-serializer-encoders>
and normalizers <component-serializer-normalizers>
.
Encoders supporting the following formats are enabled:
- JSON:
Symfony\\Component\\Serializer\\Encoder\\JsonEncoder
- XML:
Symfony\\Component\\Serializer\\Encoder\\XmlEncoder
- CSV:
Symfony\\Component\\Serializer\\Encoder\\CsvEncoder
- YAML:
Symfony\\Component\\Serializer\\Encoder\\YamlEncoder
As well as the following normalizers:
Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer
to handle typical data objectsSymfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer
for objects implementing theDateTimeInterface
interfaceSymfony\\Component\\Serializer\\Normalizer\\DateTimeZoneNormalizer
forDateTimeZone
objectsSymfony\\Component\\Serializer\\Normalizer\\DateIntervalNormalizer
forDateInterval
objectsSymfony\\Component\\Serializer\\Normalizer\\DataUriNormalizer
to transformSplFileInfo
objects in Data URIsSymfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer
to deal with objects implementing theJsonSerializable
interfaceSymfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer
to denormalize arrays of objects using a format like MyObject[] (note the [] suffix)Symfony\\Component\\Serializer\\Normalizer\\ConstraintViolationListNormalizer
for objects implementing theSymfony\\Component\\Validator\\ConstraintViolationListInterface
interfaceSymfony\\Component\\Serializer\\Normalizer\\ProblemNormalizer
forSymfony\\Component\\ErrorHandler\\Exception\\FlattenException
objects
Custom normalizers and/or encoders can also be loaded by tagging them as serializer.normalizer <reference-dic-tags-serializer-normalizer>
and serializer.encoder <reference-dic-tags-serializer-encoder>
. It's also possible to set the priority of the tag in order to decide the matching order.
Here is an example on how to load the Symfony\\Component\\Serializer\\Normalizer\\GetSetMethodNormalizer
, a faster alternative to the ObjectNormalizer when data objects always use getters (getXxx()
), issers (isXxx()
) or hassers (hasXxx()
) to read properties and setters (setXxx()
) to change properties:
# config/services.yaml
services:
get_set_method_normalizer:
class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
tags: [serializer.normalizer]
<!-- config/services.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
https://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="get_set_method_normalizer" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer">
<tag name="serializer.normalizer"/>
</service>
</services>
</container>
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
return function(ContainerConfigurator $configurator) {
$services = $configurator->services();
$services->set('get_set_method_normalizer', GetSetMethodNormalizer::class)
->tag('serializer.normalizer')
;
};
To use annotations, first add support for them via the SensioFrameworkExtraBundle:
$ composer require sensio/framework-extra-bundle
Next, add the @Groups annotations <component-serializer-attributes-groups-annotations>
to your class and choose which groups to use when serializing:
$json = $serializer->serialize(
$someObject,
'json', ['groups' => 'group1']
);
Tip
The value of the groups
key can be a single string, or an array of strings.
In addition to the @Groups
annotation, the Serializer component also supports YAML or XML files. These files are automatically loaded when being stored in one of the following locations:
- All
*.yaml
and*.xml
files in theconfig/serializer/
directory. - The
serialization.yaml
orserialization.xml
file in theResources/config/
directory of a bundle; - All
*.yaml
and*.xml
files in theResources/config/serialization/
directory of a bundle.
The metadata for the serializer is automatically cached to enhance application performance. By default, the serializer uses the cache.system
cache pool which is configured using the cache.system <reference-cache-system>
option.
The use of a name converter <component-serializer-converting-property-names-when-serializing-and-deserializing>
service can be defined in the configuration using the name_converter <reference-serializer-name_converter>
option.
The built-in CamelCase to snake_case name converter <using-camelized-method-names-for-underscored-attributes>
can be enabled by using the serializer.name_converter.camel_case_to_snake_case
value:
# config/packages/framework.yaml
framework:
# ...
serializer:
name_converter: 'serializer.name_converter.camel_case_to_snake_case'
<!-- config/packages/framework.xml -->
<framework:config>
<!-- ... -->
<framework:serializer name-converter="serializer.name_converter.camel_case_to_snake_case"/>
</framework:config>
// config/packages/framework.php
$container->loadFromExtension('framework', [
// ...
'serializer' => [
'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
],
]);
API Platform provides an API system supporting the following formats:
- JSON-LD along with the Hydra Core Vocabulary
- OpenAPI v2 (formerly Swagger) and v3
- GraphQL
- JSON:API
- HAL
- JSON
- XML
- YAML
- CSV
It is built on top of the Symfony Framework and its Serializer component. It provides custom normalizers and a custom encoder, custom metadata and a caching system.
If you want to leverage the full power of the Symfony Serializer component, take a look at how this bundle works.
serializer/normalizers serializer/custom_encoders serializer/custom_normalizer