Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTEasy + Jackson: how to exclude fields in the response?

I'm migrating my Java web application from servlet-based to JAX-RS. Since I'm using Jboss I'll also use (by default) RESTEasy.

In my servlets I use Jackson to serialize/deserialize JSON; Jackson allows me to filter programatically the inclusion/exclusion of fields, for example:

ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, 
Visibility.ANY);

String[] ignorableFieldNames = { "id", "name" };

FilterProvider filters = new SimpleFilterProvider().
addFilter("f123",SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

mapper.filteredWriter(filters).writeValueAsString(object);

RESTEasy provides Jackson support, but it seems that it is embedded transparently to the developer so I'm not able to get to the low-level to include/exclude fields. Is this feasible?

like image 903
ps0604 Avatar asked Nov 09 '14 18:11

ps0604


People also ask

How can we prevent a field from serialization in Java?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

Does RESTEasy use Jackson?

Resteasy supports both Jackson 1.9. x and Jackson 2.2.

What is RESTEasy Jackson?

Jackson, RESTEasy. RESTEasy is JBOSS provided implementation of JAX-RS specification for building RESTful Web Services and RESTful Java applications. Though this is not limited to be used in JBOSS only, and you can use with other servers also. Jackson is is a multi-purpose Java library for processing JSON data format.

What is RESTEasy?

RESTEasy is a JBoss / Red Hat project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is an implementation of the Jakarta RESTful Web Services, an Eclipse Foundation specification that provides a Java API for RESTful Web Services over the HTTP protocol.


1 Answers

You can use Jackson annotations to declaratively configure pretty much everything. In your case, @JsonIgnore should suffice.

You can use JSON views if you don't want to ignore those fields all the time.

If you can't modify the code of the class in question (say, because it's in a third-party library) mix-ins have you covered.

And if you still find that you need to access the ObjectMapper: Accessing Jackson Object Mapper in RestEasy.

See also: http://wiki.fasterxml.com/JacksonAnnotations

like image 103
Matt Ball Avatar answered Oct 14 '22 10:10

Matt Ball