javajsonspringjackson

Entity properties serialized twice


In Spring 3.3 I have an entity which is mapped to a database table. In this entity class I have all properies annotated with @JsonProperty, for instance @JsonProperty("ID"). Stepping into the controller a service is called to get such an entity by using a DAO/repository. This works well but when I send this entity back to the requestor using @ResponseBody all properties are sent twice. Once as demanded but one more time beginning lowercase until the first camel case letter occurs. An example...

public class MyEntity {
    @JsonProperty("MYSpecialSuperId")
    private String MYSpecialSuperId;

    ...

    public String getMYSpecialSsuperId() {
        return this.MYSpecialSuperId;
    }

}

After JSON stringifying the result is:

{ "MYSpecialSuperId":""9", "myspecialSuperId":"9" }

Why is the property twice in the result and why is the lettering different???

BTW: It was not my idea to let Java properties begin with an uppercase letter even yet with more than one uppercase letter.


Solution

  • Jackson's ObjectMapper uses the Java bean pattern. In other words, it expects the following

    public class Foo {
        public Object bar;
    
        public Object getBar() {...}
    
        public void setBar(Object bar) {...}
    }
    

    The getters and setters start with get and set, respectively, followed by the corresponding field name with its first letter capitalized. If you change your code to

    public class MyEntity {
        @JsonProperty("MYSpecialSuperId")
        private String mySpecialSuperId;
    
        ...
    
        public String getMySpecialSuperId() {
            return this.mySpecialSuperId;
        }
    
    }
    

    Note that the field starts with lowercase my instead of uppercase (regardless of the @JsonProperty value), I removed the extra s in getMYSpecialSsuperId and used a lowercase y. So now the field name matches the getter name and jackson knows that the property is the same and doesn't need to serialize twice.

    If you have no choice, you can follow what Katona posted in the comments and use

    @JsonAutoDetect(getterVisibility=Visibility.NONE)
    

    to make jackson ignore the getters completely and only use the fields to serialize your JSON.