symfony2: JMSSerializerBundle changes the attribute name from “className” to “class_name”

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 13:56:47

Check the documentation for the @SerializedName annotation:

http://jmsyst.com/libs/serializer/master/reference/annotations

@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.

As @mike said, you can use @SerializedName annotation to change serialized property name to arbitrary string.

Also, if you want to change naming strategy on application level. You can use the following workaround:

config.yml

parameters:
    jms_serializer.serialized_name_annotation_strategy.class: JMS\Serializer\Naming\IdenticalPropertyNamingStrategy

Also, check this issue.

If you just want to use the camel case version once, without annotations, use the IdenticalPropertyNamingStrategy:

$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(new IdenticalPropertyNamingStrategy())->build();

Inside Symfony, it make way more sense to use a compiler pass, as it avoid losing the @SerializedName annotation.

<?php

namespace AppBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class JMSSerializerCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $container->getDefinition('jms_serializer.serialized_name_annotation_strategy')
                  ->replaceArgument(0, new Reference('jms_serializer.identical_property_naming_strategy'));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!