3

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": "toto@gmail.com"
}

Here is response :

{
    "id": 3,
    "username": "toto",
    "first_name": null, // UnderscoreCase and no matching
    "name": "toti",
    "password": "blabla",
    "email": "toto@gmail.com"
}
Daiwood
  • 31
  • 1
  • 3

1 Answers1

4

You should change default property naming strategy for JmsSerializer.

In your config.yml.

jms_serializer:
    property_naming: 
        id: 'jms_serializer.identical_property_naming_strategy'
loicb
  • 587
  • 2
  • 6
  • 24
  • 1
    The caveat here is that the serialized property names are cached. I thought it didn't work at first in dev environment, because I didn't see any change and the code from the NamingStrategy class wasn't executed. Clearing the cache made it work as expected. – YetiCGN Oct 10 '19 at 13:14