简体   繁体   English

阻止JMS Serializer将CamelCase转换为UnderscoreCase

[英]Prevent JMS Serializer to convert CamelCase to UnderscoreCase

i started an API Rest with symfony 4.2 and these bundle (FOSRestBundle, JMS Serializer Bundle). 我用symfony 4.2和这些包(FOSRestBundle,JMS Serializer Bundle)开始了API Rest。 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. 我有一个Angular应用程序,它发送了许多具有firstName属性的body请求,但它与我的User属性不匹配,而它的属性名称也是firstName。

Furthermore, json response has all camelCase property changed to underscore Case. 此外,json响应已将所有camelCase属性更改为下划线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.yaml:

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

fos_rest.yaml : 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 : 这是我的json请求的正文:

{
    "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"
}

You should change default property naming strategy for JmsSerializer. 您应该更改JmsSerializer的默认属性命名策略。

In your config.yml . 在你的config.yml

jms_serializer:
    property_naming: 
        id: 'jms_serializer.identical_property_naming_strategy'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM