Prevent JMS Serializer to convert CamelCase to UnderscoreCase

1.6k views Asked by At

i started an API Rest with symfony 4.2 and these bundle (FOSRestBundle, JMS Serializer Bundle). I have an Angular application which send many request with body who has property like firstName, but it doesn't match with my User property while its property's name is firstName too.

Furthermore, json response has all camelCase property changed to underscore Case.

I've tried so many things. Nothing works. Sorry for my english, i hope you'll understand me.

Entity :

class User
{
...

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $firstName;
...
}

Controller :

  /**
   * @Post(
   *    path = "/users",
   *    name = "app_user_create"
   * )
   * @View()
   * @ParamConverter("user", converter="fos_rest.request_body")
   */
  public function createUser(Request $request, User $user, ObjectManager $em, UserRepository $userRepo, DealRepository $dealRepo)
  {
    $deal = $dealRepo->find(1);
    $user->setRegisteredAt(new \DateTime())
         ->setDeal($deal);
    $em->persist($user);
    $em->flush();


    $view = $this->view($user, 200)
                 ->setHeader('Access-Control-Allow-Origin', '*');
    return $view;
}

jms_serializer.yaml :

jms_serializer:
    visitors:
        xml_serialization:
            format_output: '%kernel.debug%'

fos_rest.yaml :

fos_rest:
    view:
        formats: { json: true, xml: false, rss: false }
        view_response_listener:  true
    serializer:
        serialize_null: true
    body_converter:
        enabled: true
    format_listener:
        rules:
            - { path: ^/, prefer_extension: true, fallback_format: json, priorities: [json] }

Here is my json request's body :

{
    "username": "toto",
    "firstName": "tutu",    // CamelCase
    "name": "toti",
    "password": "blabla",
    "email": "[email protected]"
}

Here is response :

{
    "id": 3,
    "username": "toto",
    "first_name": null, // UnderscoreCase and no matching
    "name": "toti",
    "password": "blabla",
    "email": "[email protected]"
}
1

There are 1 answers

1
loicb On

You should change default property naming strategy for JmsSerializer.

In your config.yml.

jms_serializer:
    property_naming: 
        id: 'jms_serializer.identical_property_naming_strategy'