Ignore a java bean field while converting to jSON
I am having a java bean and sending JSON as response , In that java bean I want to have some transient fields , that should not come into JSON .
@XmlRootElement(name = "sample")
class Sample{
private String field1;
@XmlTransient
private String transientField;
//Getter and setters
public String toJSON() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
}
When I am calling toJSON method I am still getting "transientField" in JSON.
And I have a get rest API that returns this Sample JSON as response.
@GET
@Path("/somePath/")
@Produces({"application/json"})
Sample getSample();
In this response also I am getting that transient field . Am I doing something wrong? Please help me to do this .
method 1: use annotation @JsonIgnoreProperties("fieldname") to your POJO
example : @JsonIgnoreProperties(ignoreUnknown = true, value = {"fieldTobeIgnored"})
method 2:@JsonIgnore for a specific field that is to be ignored deserializing JSON