Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to hide some fields of an object that are being mapped to JSON by Jackson

Tags:

java

json

jackson

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?

like image 285
sonicboom Avatar asked Feb 05 '13 13:02

sonicboom


People also ask

How do I exclude fields in JSON?

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.

How do I ignore a field in JSON response Jackson?

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.

How do I ignore properties in 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.

How do I ignore properties in Jackson?

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.


1 Answers

You have two options:

  1. 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.)

  2. 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; } 
like image 148
Ravi Khakhkhar Avatar answered Sep 20 '22 01:09

Ravi Khakhkhar