Jackson Not Overriding Getter with @JsonProperty

前端 未结 10 2088
醉话见心
醉话见心 2021-02-12 06:23

JsonProperty isn\'t overriding the default name jackson gets from the getter. If I serialize the class below with ObjectMapper and jackson I get

<
10条回答
  •  甜味超标
    2021-02-12 06:29

    I recently came across another interesting twist on this issue. We started using the Hibernate5Module to help with some lazy loading issues. Furthermore, we use Groovy so we are not defining getters and setters.

    It turns out that the Hibernate Module seems to interfere with the @JsonProperty annotation. Specifically if you have something annotated with @Transient So, if you have something like:

    @Transient
    @ApiModelProperty(required = true)
    @JsonProperty("alternateName")
    String property
    

    You won't see the alternateName in the JSON. Furthermore, your clients will likely have trouble with their POSTs and PUTs! To fix this, you can use a simple workaround. Define the getters and setters for the internal name you need to use(*) and don't use the value attribute on @JsonProperty So this works:

    @Transient
    @ApiModelProperty(required = true)
    @JsonProperty
    String alternateName
    
    void setProperty(String property) {
        this.alternateName = property
    }
    
    @JsonIgnore
    String getProperty() {
        this.alternateName
    }
    

    Note the use of the @JsonIgnore on the getter. If you don't, your framework will probably pick it up and you'll have duplicate entries for the same thing in your JSON.

    Anyhow - I'm hoping this helps someone!

    (*)We were trying to adhere to a particular interface, thus enforcing the name internally. However, the exposed API needed a different, user-friendly name.

提交回复
热议问题