catdog
catdog

Reputation: 87

Custom naming strategy and @JsonProperty in Jackson

I'm trying to override property name specified in @JsonProperty during serialization, but get both old and new named properties in the resulting json.

Entity:

class Bean {

    @JsonProperty("p")
    String prop;

    @JsonCreator
    Bean(@JsonProperty("p") String prop) {
        this.prop = prop;
    }
}

Serializing code:

ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
            @Override
            public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
                return "prop";
            }
        });
System.out.println(mapper.writeValueAsString(new Bean("test")));

Results in:

{"p":"test","prop":"test"}

Accrding to Jackson's code, this happens because constructor parameters are also annotated with @JsonProperty. I'm using Jackson 1.9.5.

Is there a way to disable constructor parameters and get {"prop":"test"} ? Thanks for help in advance!

Upvotes: 0

Views: 3968

Answers (1)

StaxMan
StaxMan

Reputation: 116472

There is no way to directly disable annotations, but if you want to block their effects, you can sub-class JacksonAnnotationIntrospector, and override logic used for finding @JsonProperty annotation (or @JsonCreator).

Upvotes: 1

Related Questions