Reputation: 101
why do we put @JsonProperty
on Setters and Getters in Java DTO, and what is the different between that and putting @JsonProperty
on the property?
and if we need to put it on both to be reflected, then does it work with @Data
lombok annotations?
Upvotes: 0
Views: 2887
Reputation: 5155
The Jackson JSON library looks for those anontations to know what JSON fields exist for serialization (conversion from java object to string), or deserialization (conversion from string to java object).
The support for annotating both fields and methods is a convenience to support different configurations that developers may have. With that said, best practice is to use model objects that have the "properties" (i.e. fields) with getters and setters that use standard naming. When following this practice, the developer can choose to annotate either the fields or the methods.
An example why you might need to anotate a method and not a field - if you have an object that inherits a protected field from a base-class and cannot add the annotation to the base class. In that case, you can add a getter for the field to the derived class and annotate it instead. But please only do this if you cannot follow the best-practice.
Upvotes: 1
Reputation: 98
If you want something to be mapped to your object, you put it on setters, if you want it to be exported with that json property you would use it on a getter, you can basically choose if you want it to be only serializable or only deserializable that way.
To be honest I never used it that way as I never needed to have one without the other so I always used it on fields. My advice is just use it on properties and it works on both.
And yes it works on lombok's @Data.
Upvotes: 1