Symfony News

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"}

Be trained by Symfony experts - 2018-11-5 Paris - 2018-11-5 Paris - 2018-11-7 Paris


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook