Tom Bunting
Tom Bunting

Reputation: 1865

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, e.g:

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), e.g:

objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

Problem:

This works exactly as expected with normal java properties, i.e. 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?

Upvotes: 0

Views: 1260

Answers (1)

StaxMan
StaxMan

Reputation: 116522

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/

Upvotes: 1

Related Questions