I have a class that has some additional getters for derived values. When I serialize this with jackson objectmapper, it writes out that field as well. Is there a way to avoid that?
example -
public class CustomPath implements Serializable {
private String path;
private String name;
private String extension = ".txt";
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public CustomPath(@JsonProperty("path") String path, @JsonProperty("name") String name) {
this.path = path;
this.name = name;
}
public String getPath()
{ return this.path;}
public void setPath(String path)
{ this.path = path;}
public String getName()
{ return this.name;}
public void setName(String name)
{ this.name = name;}
public String getExtension()
{ return this.extension;}
public void setExtension(String extension)
{ this.extension = extension;}
public String getFullPath() //do not want to serialize this
{ return this.path +"/" + this.name + this.extension;}
}
The json for a class like this looks like -
{
path: somepath
name: somename
extension: .txt
fullPath: somepath/somename.txt
}
But I do not want to serialize 'fullPath' in the example above. Is there any way I can avoid that?
You need to annotate the getFullPath()
method with @JsonIgnore
:
@JsonIgnore
public String getFullPath() // do not want to serialize this
{
return this.path + "/" + this.name + this.extension;
}
Then the JSON output will look like this:
{
"path" : "somePath",
"name" : "someName",
"extension" : ".txt"
}