JMS Serializer: how to use camel case for properties

走远了吗. 提交于 2019-12-01 01:12:33

问题


I'm using FOS Rest bundle and JMS Serializer to create a REST Api. The problem is I would like to keep the property names in the JSON response camel cased instead of using _.

For example, I have a property called employeeIdentifier, by default that gets converted to employee_identifier.

I saw that there's an option in the config to disable the lowercase and get rid of the _, but then it becomes EmployeeIdentifier.

Is there any way that JMS Serializer keeps the original name of the property? Thanks in advance


回答1:


I found a way to do it globally, if you want to keep the property names as is you need to use the IdenticalPropertyNamingStrategy

There are several ways to accomplish this, first by changing the config(Thanks @Phantom):

#config.yml
jms_serializer:
    property_naming: 
        id: 'jms_serializer.identical_property_naming_strategy'

Second, you could override the default alias for this

services:
    jms_serializer.naming_strategy:
        alias: jms_serializer.identical_property_naming_strategy

The bundle defines these https://github.com/schmittjoh/JMSSerializerBundle/blob/master/Resources/config/services.xml so you should be able to override them

Another way to do it is when you initialize the builder:

$serializebuilder = JMS\Serializer\SerializerBuilder::create();
$serializebuilder->setPropertyNamingStrategy(new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy());
$serializer = $serializebuilder->build();



回答2:


Having upgraded jms/serilizer-bundle from 1.1 to 2.2 the parameter hack described above did not work. You can override the service definition as follows:

#app/config/services.yml
services:
    ....
    jms_serializer.serialized_name_annotation_strategy:
        class: JMS\Serializer\Naming\SerializedNameAnnotationStrategy
        arguments:
            - '@jms_serializer.identical_property_naming_strategy'



回答3:


I found a way to do it but it's not the best way I think, there's an annotation SerializedName wich allows you to override the property serialization. The problem is that you have to do it one by one on every property with camel case, here's the documentation: YAML: http://jmsyst.com/libs/serializer/master/reference/yml_reference Annotation: http://jmsyst.com/libs/serializer/master/reference/annotations#serializedname



来源:https://stackoverflow.com/questions/43529287/jms-serializer-how-to-use-camel-case-for-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!