阻止JMS序列化程序将CamelCase转换为UnderscoreCase

时间:2019-05-08 13:12:22

标签: json fosrestbundle jmsserializerbundle symfony-4.2 naming-strategy

我用symfony 4.2和这些捆绑软件(FOSRestBundle,JMS序列化工具捆绑软件)启动了API Rest。 我有一个Angular应用程序,该应用程序发送带有具有诸如firstName之类的属性的正文的许多请求,但是它的属性名称也为firstName时,它与我的User属性不匹配。

此外,json响应将所有camelCase属性更改为下划线Case。

我尝试了很多事情。什么都没有。 对不起,我的英语,希望您能理解我。

实体:

class User
{
...

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

控制器:

  /**
   * @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] }

这是我的json请求的正文:

{
    "username": "toto",
    "firstName": "tutu",    // CamelCase
    "name": "toti",
    "password": "blabla",
    "email": "toto@gmail.com"
}

这是回应:

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

1 个答案:

答案 0 :(得分:0)

您应该更改JmsSerializer的默认属性命名策略。

在您的config.yml中。

jms_serializer:
    property_naming: 
        id: 'jms_serializer.identical_property_naming_strategy'