FasterXML / jackson-databind

General data-binding package for Jackson (2.x): works on streaming API (core) implementation(s)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Serialization of a class that is fully annotated with JsonProperty is tricked by getter name

davidmoten opened this issue · comments

The test below fails, serialization of the class produces {"isValue":true,"value":true} despite being fully annotated with JsonProperty. I'd like it to produce {"isValue":true}.

If I rename the isValue getter method to value it works.

A workaround is to annotate the getter with @JsonIgnore.

Is this expected behaviour? I couldn't see a SerializationFeature to turn this behaviour off.

    @Test
    public void testSerializationWhenIsGetterPresent() throws JsonProcessingException {
        WithIs a = new WithIs(true);
        String json = new ObjectMapper().writeValueAsString(a);
        System.out.println(json);
        assertEquals("{\"isValue\":true}", json);
    }
    
    public static class WithIs {

        @JsonProperty("isValue")
        private boolean isValue;

        @JsonCreator
        public WithIs(
                @JsonProperty("isValue") boolean isValue) {
            this.isValue = isValue;
        }

        public boolean isValue() {
            return isValue;
        }
    }

Version Information

2.17.0

Yes, behavior is as expected because inferred ("implicit") property name from:

public boolean isValue() {

is value, not isValue. "is" is considered equivalent to "get" prefix, for case of boolean/Boolean valued properties. Fields and constructor parameters on the other hand use name as-is without considering prefixes. So that's why Bean introspection logic infers 2 separate properties here.

This is along with my understanding of Bean naming convention; I know some other usage (like, say, Kotlin naming convention) differs.

So unfortunately annotation is needed on isValue() method (but not on field -- and on constructor parameter only if ParameterNamesModule not used).