Reputation: 1159
I am working on a site that uses promo codes to potentially provide users free memberships to the site. The level that a member signs up at is an attribute of a promo code object and stored in the database as an int, either 1 or 2. However, the only time the member level attribute is relevant to the UI of the site is for a landing page associated with a specific promo code. So for that case, I don't want the member level to be ignored by JSON. After a user returns to the site and has a promo code object associated with their account, we no longer care about their member level so I would like the member level attribute to be ignored by JSON.
So my question is this, is it possible to set an object's attribute to @JSONIgnore
on a per access basis, or can an attribute only be ignored or not ignored? In other words is there a method like object.getAttribute().setAttributeJSONIgnore(true | false)
?
Upvotes: 9
Views: 21862
Reputation: 71
I've done something similar with JSONViews (http://wiki.fasterxml.com/JacksonJsonViews).
You'd create a Base View and then extend it with a PromoPage View. In the object you're serializing, you'd add the annotation to each property. So the ones you want to appear every time would be
@JsonView(Views.Base.class)
String name;
The properties you only wanted to show on those certain Promo Pages would be something like
@JsonView(Views.PromoPage.class)
Integer memberLevel;
Then if you have different JAX-RS methods for getting the promopages than the other landing page, you can annotate the methods with the appropriate View like so
@JsonView(Views.Base.class)
@GET
@Produces(MediaType.APPLICATION_JSON )
public Object getNormalLandingPageInfo() {
...
}
@JsonView(Views.PromoPage.class)
@GET
@Produces(MediaType.APPLICATION_JSON )
public Object getPromoLandingPageInfo() {
...
}
If you don't, in your logic, you can do whatever you want to determine when to show the PromoPage View, then do something like this
if (showPromoPage)
objectMapper.writeValueUsingView(out, object, Views.PromoPage.class);
else
objectMapper.writeValueUsingView(out, object, Views.Base.class);
Upvotes: 3
Reputation: 116522
No. Annotation-based approaches are static, since although you could use custom AnnotationIntrospector
, resulting JsonSerializer
instances are reused since their construction is costly.
But there are ways to filter out properties, check out "Filtering Properties" article, for example.
Upvotes: 7