New in Symfony 4.2: Simpler custom serialized names

Contributed by
Fabien Bourigault
in #28505.

The Serializer component is able to transform property names when serializing objects. For example, it can transform camel-cased properties like $firstName into snake-cased values like first_name.

For more complex cases, you can create name converters to map PHP property names to serialized names arbitrarily. In Symfony 4.2 we added another simpler way to do that. You can now configure name conversion rules using metadata and it works with PHP annotations (@SerializedName), XML config (serialized-name attribute) and YAML config (serialized_name key).

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

use Symfony\Component\Serializer\Annotation\SerializedName;

class Person
{
    /** @SerializedName("customer_name") */
    private $firstName;

    public function __construct(string $firstName)
    {
        $this->firstName = $firstName;
    }

    // ...
}

When this object is serialized, the $firstName property will be called customer_name instead of first_name:

1
2
$serialized = $serializer->serialize(new Person('Jane'));
// {"customer_name": "Jane"}

Comments

This is super useful, thanks!
Awesome ! Does it work with serialization groups, to transform the name only depending a group ?
This is great and is going to make complex serialization clearer :)
Great addition, thanks Fabien!
Login with SymfonyConnect to post a comment