如何在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:
Replace
IdenticalPropertyNamingStrategywithCamelCaseNamingStrategy
This naming strategy defaults to preserving camelCase property names (which matches your desired global behavior), but it respectsserialized-nameoverrides 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();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:
idPublicwill serialize toid(as specified inserialized-name)nameandotherPropertywill remain in camelCase without needing individual configurations
Why your virtual property attempt failed
The sameIdenticalPropertyNamingStrategyrestriction applied here—it was overriding theserialized-namefor your virtual property. WithCamelCaseNamingStrategy, your virtual property configuration would also work as expected if you need to use that approach later.
Extra Notes:
- The default behavior of
CamelCaseNamingStrategyis to output property names exactly as they are (camelCase), so it matches the global behavior you wanted fromIdenticalPropertyNamingStrategy. - Double-check that your metadata directory path is correct, so the serializer can properly load your XML configurations.
内容的提问来源于stack exchange,提问作者user1032531

