You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JMS Serializer全局相同命名策略下覆盖序列化名称?

How to Override Serialization Names Globally in JMS Serializer?

The core issue here is that when you use IdenticalPropertyNamingStrategy, it overrides and ignores any serialized-name configurations in your XML metadata. This strategy is designed to force the serialized output name to be exactly identical to the property name, which takes precedence over custom mappings.

Here's the fix to keep global camelCase output while allowing individual overrides:

  1. Replace IdenticalPropertyNamingStrategy with CamelCaseNamingStrategy
    This naming strategy defaults to preserving camelCase property names (which matches your desired global behavior), but it respects serialized-name overrides in your metadata. Update your serializer builder code to:

    $serializer= \JMS\Serializer\SerializerBuilder::create() 
        ->setDebug(true) 
        ->addMetadataDir(APP_ROOT.'/config/serializer') 
        ->setPropertyNamingStrategy(new \JMS\Serializer\Naming\CamelCaseNamingStrategy()) 
        ->build();
    
  2. Keep your existing XML metadata as-is
    Your original configuration will now work correctly, no changes needed:

    <?xml version="1.0" encoding="UTF-8" ?>
    <serializer>
    <class name="Fully\Qualfied\ClassName" exclusion-policy="ALL">
    <property name="idPublic" serialized-name="id" expose="true"/>
    <property name="name" expose="true"/>
    <property name="otherProperty" expose="true"/>
    </class>
    </serializer>
    

    After this change:

    • idPublic will serialize to id (as specified in serialized-name)
    • name and otherProperty will remain in camelCase without needing individual configurations
  3. Why your virtual property attempt failed
    The same IdenticalPropertyNamingStrategy restriction applied here—it was overriding the serialized-name for your virtual property. With CamelCaseNamingStrategy, your virtual property configuration would also work as expected if you need to use that approach later.

Extra Notes:

  • The default behavior of CamelCaseNamingStrategy is to output property names exactly as they are (camelCase), so it matches the global behavior you wanted from IdenticalPropertyNamingStrategy.
  • Double-check that your metadata directory path is correct, so the serializer can properly load your XML configurations.

内容的提问来源于stack exchange,提问作者user1032531

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:44:34