I have inherited a certain bit code that has the @JsonProperty annotation on getter/setters. The purpose is so that when the object is serialized using the Jackson library, the fields have that specific name.
Current code:
private String fileName;
@JsonProperty("FILENAME")
public String getFileName()
{
return fileName;
}
@JsonProperty("FILENAME")
public void setFileName(String fileName)
{
this.fileName = fileName;
}
Now for another tool, I need to annotate the field with JsonProperty as well. So this will be my changed code:
@JsonProperty("FILENAME")
private String fileName;
@JsonProperty("FILENAME")
public String getFileName()
{
return fileName;
}
@JsonProperty("FILENAME")
public void setFileName(String fileName)
{
this.fileName = fileName;
}
Has anyone used this same annotation on both – the field as well as the getter/setters? I looked around on the net but didn't see anything.
I have compiled & run the code but I'm not sure if this would this cause any problems down the road. Any thoughts on this?
Best Answer
My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:
For eg. consider a slight modification of your case:
Both
fileName
field, and methodgetFileName
, have the correct property name offileName
andsetFileName
has a different onefileName1
, in this case Jackson will look for afileName1
attribute in json at the point of deserialization and will create a attribute calledfileName1
at the point of serialization.Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of
fileName
, it would just pick one of them as the attribute(FILENAME
), and had any on of the three differed, it would have thrown an exception: