1

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?

nit
  • 85
  • 1
  • 5

1 Answers1

1

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"
}
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • Thanks @Thomas Fritsch for your quick response. I actually tried that but I still see it in my serialized json. Is there any setting I need to make on the object mapper to honor that annotation? Thanks. – nit Feb 09 '21 at 22:31
  • @nit This should work without any additional configuration of the `ObjectMapper`. .Actually I have added `@JsonIgnore` to your posted code, tested it, and for me it works fine. – Thomas Fritsch Feb 09 '21 at 23:09
  • this actually worked. I had another method which was returning this from another class which needed to be annotated as well. Thanks much!! – nit Feb 09 '21 at 23:41