Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
SheppardDigital Avatar asked Aug 31 '16 17:08

SheppardDigital


2 Answers

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

like image 180
Jon Peterson Avatar answered Sep 30 '22 18:09

Jon Peterson


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

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

like image 20
Martin Frey Avatar answered Sep 30 '22 19:09

Martin Frey