Custom serialized and deserialized field names with lombok

倖福魔咒の 提交于 2021-02-07 09:52:10

问题


Is there a way to specify different serialized/deserialized JSON field names without having to write out both getter and setter methods explicitly, perhaps using lombok getters and setters?

As similar to this example, the following code permits incoming JSON to be deserialized to a different POJO field name. It also causes the POJO field name to be serialized as is:

public class PrivacySettings {
    private String chiefDataOfficerName;

    @JsonProperty("CDO_Name__c")
    private void setChiefDataOfficerName(String chiefDataOfficerName) {
        this.chiefDataOfficerName = chiefDataOfficerName;
    }

    @JsonProperty("chiefDataOfficerName")
    private String getChiefDataOfficerName() {
        return chiefDataOfficerName;
    }
}

This seems verbose, but I haven't been able to get this to work with @Getter and @Setter. I did see that Jackson supports @JsonAlias which would probably help in this particular example, but I also have need to serialize with a different name.

Seems like this should be very simple, something like:

@Getter
@Setter
public class PrivacySettings {
    @JsonSetter("CDO_Name__c")    
    @JsonGetter("chiefDataOfficerName")    
    private String chiefDataOfficerName;
}    

But of course this is not valid.


回答1:


I particularly don't see anything wrong with a getter and a setter for this situation.


However, if you want to try, since v0.11.8 Lombok supports an experimental feature to add annotations to generated getters and setters. See the documentation:

To put annotations on the generated method, you can use onMethod=@__({@AnnotationsHere}); to put annotations on the only parameter of a generated setter method, you can use onParam=@__({@AnnotationsHere}). Be careful though! This is an experimental feature. For more details see the documentation on the onX feature.

The syntax for this feature depends on JDK version. For JDK 8, you'll have:

public class PrivacySettings {

    @Setter(onMethod_ = { @JsonSetter("CDO_Name__c") })
    @Getter(onMethod_ = { @JsonGetter("chiefDataOfficerName") })
    private String chiefDataOfficerName;
}

For JDK 7, the syntax is:

public class PrivacySettings {

    @Setter(onMethod = @__({ @JsonSetter("CDO_Name__c") }))
    @Getter(onMethod = @__({ @JsonGetter("chiefDataOfficerName") }))
    private String chiefDataOfficerName;        
}

For further details, check the @Getter and @Setter documentation. Also see this answer for details on @__().



来源:https://stackoverflow.com/questions/49886553/custom-serialized-and-deserialized-field-names-with-lombok

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!