Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
Punter Vicky Avatar asked Jan 20 '26 12:01

Punter Vicky


1 Answers

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.

like image 101
Darshan Mehta Avatar answered Jan 23 '26 03:01

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!