New in Symfony 5.3: Inlined Serialization Context
![Avatar of Javier Eguiluz](https://connect.symfony.com/api/images/17170f22-52c0-4adf-a75d-29cb01d53176.png?format=28x28)
Symfony 5.3 is backed by:
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Maxime Steinhausser
in #39399.
The Serializer component provides a mechanism to configure the way data is serialized/deserialized: the context options. These options are passed as an optional argument of the serialize/deserialize methods.
In Symfony 5.3 we've improved the serializer so you can define the context
as part of the mapping information thanks to a new Serializer\Context
annotation/attribute.
For example, to define how some datetime property should be formatted, use the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
class SomeClass
{
/**
* @Serializer\Context({ DateTimeNormalizer::FORMAT_KEY = 'Y-m-d' })
*/
public \DateTime $date;
// In PHP 8 applications you can use PHP attributes instead:
#[Serializer\Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
public \DateTime $date;
}
The annotation/attribute supports different contexts for normalization/denormalization and it can also define serialization groups:
1 2 3 4 5 6 7 8 9 10 11
#[Serializer\Context(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'],
denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::COOKIE]
)]
public \DateTime $date;
#[Serializer\Context(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339],
groups: ['extended']
)]
public \DateTime $date;
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
![Avatar of Grégoire Pineau](https://connect.symfony.com/api/images/90f28e69-9ce9-4a42-8b0e-e8c7fcc27713.png?format=48x48)
![Avatar of Anthony MARTIN](https://connect.symfony.com/api/images/0025a865-3507-43a0-883a-7430e59e4df0.png?format=48x48)
![Avatar of Richard Lynskey](https://connect.symfony.com/api/images/fba7eb46-59f0-4dfe-8b08-d2d0e40b4888.png?format=48x48)
![Avatar of CJayHe](https://connect.symfony.com/api/images/8ebe4ac0-af4c-4fbf-9338-c1f436f3d1d1.png?format=48x48)
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.