SheppardDigital
SheppardDigital

Reputation: 3265

Spring Boot @JsonIgnore on entity, sometimes I want a property to be returned as Json

I have an API I'm building using Spring Boot. The API will return recipes.

I have an @Entity which contains all of the properties for my recipes, including things such as the category, ingredients and the steps needed to make the recipe.

I have two API endpoints, once which returns a list of recipes (/recipes), and another which returns details on an individual recipe (/recipes/49).

My problem is that in the endpoint that lists recipes (/recipes) I don't want to return properties such as ingredients and steps, but I do want to return them in the endpoint which provided details on an individual recipe (/recipes/49). The problem is that using @JsonIgnore always removed the properties from ALL JSON responses, which is not what I need.

I've tried to do some research but can't seem to find a solution, and the only way I can think about doing this is to always loop through each recipe and populate some kind of response object which only has the necessary properties for the endpoint that they're being returned in, but this doesn't 'feel' right.

Is someone able to confirm how you would go about doing this?

Upvotes: 6

Views: 4472

Answers (3)

SheppardDigital
SheppardDigital

Reputation: 3265

I have come across one solution which works, but requires the creation of a new object for my Recipes, a kind of RecipeSummary object.

http://glennpaulley.ca/conestoga/2015/05/jpa-and-native-sql-queries-part-deux/

It uses @SqlResultSetMapping to map a query to a none-entity class.

Upvotes: 0

Jon Peterson
Jon Peterson

Reputation: 2996

This blog post details how to use @JsonView annotations and view classes to specify which fields to return from various endpoints.

Upvotes: 4

Martin Frey
Martin Frey

Reputation: 10075

Take a look at my jackson addon. I developed it exactly for this purpose.

https://github.com/Antibrumm/jackson-antpathfilter

Upvotes: 1

Related Questions