Skip to content

How to Create your Custom Name Converter

Edit this page

The Serializer Component uses name converters to transform the attribute names (e.g. from snake_case in JSON to CamelCase for PHP properties).

Imagine you have the following object:

1
2
3
4
5
6
7
namespace App\Model;

class Company
{
    public string $name;
    public string $address;
}

And in the serialized form, all attributes must be prefixed by org_ like the following:

1
{"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}

A custom name converter can handle such cases:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace App\Serializer;

use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class OrgPrefixNameConverter implements NameConverterInterface
{
    public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string
    {
        // during normalization, add the prefix
        return 'org_'.$propertyName;
    }

    public function denormalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string
    {
        // remove the 'org_' prefix on denormalizing
        return str_starts_with($propertyName, 'org_') ? substr($propertyName, 4) : $propertyName;
    }
}

7.1

Accessing the current class name, format and context via normalize() and denormalize() was introduced in Symfony 7.1.

Note

You can also implement AdvancedNameConverterInterface to access the current class name, format and context.

Then, configure the serializer to use your name converter:

1
2
3
4
5
# config/packages/serializer.yaml
framework:
    serializer:
        # pass the service ID of your name converter
        name_converter: 'App\Serializer\OrgPrefixNameConverter'

Now, when using the serializer in the application, all attributes will be prefixed by org_:

1
2
3
4
5
6
7
// ...
$company = new Company('Acme Inc.', '123 Main Street, Big City');

$json = $serializer->serialize($company, 'json');
// {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}
$companyCopy = $serializer->deserialize($json, Company::class, 'json');
// Same data as $company
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version