New in Symfony 4.2: Simpler custom serialized names
October 25, 2018 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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"}
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 are closed.
To ensure that comments stay relevant, they are closed for old posts.