Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Alias for attributes #15171

Closed
@estahn

Description

@estahn

It would be very helpful to have the possibility to specify an alias for an attribute. This is the same as serialized_name in JMSSerializer".

@SerializedName
This annotation can be defined on a property to define the serialized name for a property. If this is not
defined, the property will be translated from camel-case to a lower-cased underscored name, e.g.
camelCase -> camel_case.

Here is an example YAML:

AppBundle\Entity\Product:
    attributes:
        id:
            groups: [default]
        name:
            groups: [default]
        brand.name:
            alias: brand
            groups: [default]

I wonder about the general take on this.

This was also mentioned in #14924 .

My current workaround is using a custom NameConverter.

use Symfony\Component\Serializer\Exception\UnsupportedException;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class ArrayNameConverter implements NameConverterInterface
{
    protected $map = [];

    /**
     * @param array $map
     */
    public function __construct(array $map)
    {
        $this->map = $map;
    }

    public function normalize($propertyName)
    {
        return isset($this->map[$propertyName]) ? $this->map[$propertyName] : $propertyName;
    }

    public function denormalize($propertyName)
    {
        throw new UnsupportedException('This method needs to be implemented.');
    }
}

$normalizer = new ObjectNormalizer($classMetadataFactory, new ArrayNameConverter(['brand.name' => 'brand']));

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions