Punter Vicky
Punter Vicky

Reputation: 16992

Exclude few fields in java bean from being sent in rest response - Spring Boot

I have a bean which I am returning as part of one of my controller methods. There are few fields in the bean that I have processing but do not want them to be returned back to the consumer. Is there a way to exclude some of the fields from being returned without having to create a new bean that only has the elements that I need to return?

Upvotes: 3

Views: 5210

Answers (2)

Ashiq A
Ashiq A

Reputation: 11

When the class is turned in to JSON whats actually happening is its calling all methods in that class that start with get, and that json field is named whatever comes after get. for example getFirstNaa_aame(){return firstName} will return the json "firstNaa_aame" : "<firstname>".

so one way is to remove the get method. or rename the getFirst name to geTFirstName(Not reccommended) or use @Darshan Meha's @JsonIgnore on that get method

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30819

Spring boot by default uses Jackson to serialise/deserialise json. In Jackson, you can exclude a field by annotating it with @JsonIgnore, e.g.

public class Bean {

@JsonIgnore
private String field1;

private String field2

//getters and setters

}

By doing this, field1 of Bean class will not get sent in the response. Also, if this bean is used in the request, this field will not be deserialised from request payload.

Here's the documentation for JsonIgnore.

Upvotes: 5

Related Questions