0

Hello dear Stackoverflow community,

I have 2 PHP class (considered as DTO) that I'm using to set the body of my HTTP calls. Each DTO is used for a different API with different naming strategies (one is using camelCase and the other one is using snake_case.

I can't find a solution to inject my JMS serlializer with a different naming strategy for each of these classes.

Here is my current configuration for JMS :

jms_serializer:
    default_context:
        serialization:
            serialize_null: false
        deserialization:
            serialize_null: false
    property_naming:
        id: 'jms_serializer.identical_property_naming_strategy'

Here is my services definition :

ApiBundle\Services\ApiOneService:
    arguments:
        - '%external_components%'
        - '@jms_serializer'
        - '@monolog.logger'

ApiBundle\Service\ApiTwoService:
    arguments:
        - '%external_components%'
        - '@jms_serializer'

Note : I can't use the @SerializedName annotation because it's not working if you specify a naming strategy as stated in the JMS documentation https://jmsyst.com/libs/serializer/master/reference/annotations#serializedname

Is there a way to "copy" my JMS service in my services.yml and just change the naming strategy for my ApiTwoService ? Or any other solution ?

Best regards.

Ga3tan
  • 85
  • 1
  • 12
  • Hi, did you checked [this issue](https://github.com/schmittjoh/serializer/issues/128) on the github? – Evgeny Ruban Apr 07 '20 at 13:55
  • Thanks for your help Eugene, unfortunately it's changing the naming strategy for all properties in all classes. I would like to use a specific naming strategy for a specific class. Like camelCase for the properties of class A and snake_case for the properties class B. – Ga3tan Apr 07 '20 at 14:00
  • couldn't you just build a different "local" serializer in your second service? – Jakumi Apr 07 '20 at 15:41

1 Answers1

0

you can set the NamingStrategy on creating the Serializer, but for the preview with Swagger its not working for me

 public function getApiResponse($entity, $groups = [], $asResponse = true)
{
    $serializer = SerializerBuilder::create();
    $serializer->setPropertyNamingStrategy(new SerializedNameAnnotationStrategy(new IdenticalPropertyNamingStrategy()));
    $serializer = $serializer->build();

    $context = null;
    if (sizeof($groups) > 0) {
        $context = SerializationContext::create()->setGroups($groups);
    }

    $result = $serializer->serialize($entity, 'json', $context);
    if ($asResponse == false) {
        return $result;
    }

    return new JsonResponse($result, 200, [], true);
}