简体   繁体   中英

PropertyNamingStrategy ignored when using @JsonAnyGetter

Scenario:

Using Jackson 2.4.5 I have a dynamic bean to be serialised into JSON which can store some of its state in 'optional' properties in an internal map and uses @JsonAnyGetter on an accessor method that returns this map, eg:

public class DynamicJsonView {

private final Map<String, Object> optionalProperties = new HashMap<>();

private final String rqdProperty = "blah";

public String getRqdProperty() {
    return rqdProperty;
}

public DynamicJsonView() {
    optionalProperties.put("PROP_1", "value 1");
    optionalProperties.put("PROP_2", "value 2");
    optionalProperties.put("PROP_3", "value 3");
    // etc - in reality populated from another map
}

@JsonAnyGetter
public Map<String, Object> any() {
    return Collections.unmodifiableMap(optionalProperties);
} 
}

Note the map keys are UPPER_CASE. When we setup our ObjectMapper we set the following naming strategy to convert properties to lower case (and replace camelCase with snake_case), eg:

objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

Problem:

This works exactly as expected with normal java properties, ie rqdProperty in the example above converts to rqd_property in the JSON serialized form, but the naming strategy is seemingly ignored for the map 'properties', with the upper case keys appearing unmodified. Having debugged the jackson LowerCaseWithUnderscoresStrategy#translate method and watched the input parameter values passed in as the object is serialised, it seems the keys are never passed through the naming strategy.

The obvious workaround is to pre-process the map keys and convert them all to lower case, but I wondered if there's something I'm missing with regards to the property naming strategy, or if this is simply a limitation of the library?

This is as designed since NamingStrategy is only applied to actual concrete properties, and not for Map keys, or "any" properties.

But if ability to include name mangling for any properties sounds like a good idea, you could request a new feature to do that: it could be enabled (for example) by a flag of @JsonAnySetter :

https://github.com/FasterXML/jackson-databind/issues/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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