I have a User class that I want to map to JSON using Jackson.
public class User { private String name; private int age; prviate int securityCode; // getters and setters }
I map this to a JSON string using -
User user = getUserFromDatabase(); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(user);
I don't want to map the securityCode
variable. Is there any way of configuring the mapper so that it ignores this field?
I know I can write custom data mappers or use the Streaming API but I would like to know if it possible to do it through configuration?
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
Ignore All Fields by Type Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly: @JsonIgnoreType public class SomeType { ... } More often than not, however, we don't have control of the class itself.
You have two options:
Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
Or, you can use the @JsonIgnore
annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.
@JsonIgnore public int getSecurityCode(){ return securityCode; }
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