@JsonIgnore
@Xmltransient
private int id
I want to understand the purpose of using these two annotations on top of the some property/field @JsonIgnore & @Xmltransient with some example.
I already gone through different websites.
@XmlTransient is a JAXB annotation that signals marshallers to ignore a field/property.@JsonIgnore is a proprietary Jackson annotation that signals Jackson to ignore a field/property.Since the question asks about @JsonIgnore I'm assuming you're looking for how these are both used by Jackson. Which annotation to use depends on which AnnotationIntrospector you use with your ObjectMapper.
@XmlTransient is read by the JaxbAnnotationIntrospector which attempts to honor JAXB annotations during marshalling to json.@JsonIgnore is read by the JacksonAnnotationIntrospector which reads standard Jackson annotations for marshalling.Example without @XmlTransient:
public class User
{
private String firstName;
private String lastName;
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getUserName()
{
return firstName + "_" + lastName;
}
}
Sample Jackson output:
{
firstName: "Jay",
lastName: "Unit",
userName: "Jay_Unit"
}
Jackson recognizes userName as a property because getUserName() looks like a field accessor. In this case, getUserName() contains the business logic for constructing the userName property and including this in the resulting json may be desired. However, if you don't need the userName property or if the json will be unmarshalled back into the User class, sending userName over the wire is a waste. You can prevent Jackson from marshalling the field by using @XmlTransient or @JsonIgnore.
Example with @XmlTransient on property:
public class User
{
private String firstName;
private String lastName;
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
@XmlTransient
public String getUserName()
{
return firstName + "_" + lastName;
}
}
Sample Jackson output:
{
firstName: "Jay",
lastName: "Unit"
}
Example with @JsonIgnore on fields:
public class User
{
@JsonIgnore
private String firstName;
@JsonIgnore
private String lastName;
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getUserName()
{
return firstName + "_" + lastName;
}
}
Sample Jackson output:
{
userName: "Jay_Unit"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With