JMS Serializer: how to use camel case for properties

petekaner picture petekaner · Apr 20, 2017 · Viewed 10.8k times · Source

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

Answer

Chase picture Chase · Apr 20, 2017

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();