2

I have made a service that returns an array of UserSettings objects:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/")
public Response getBulkSettings(@QueryParam("fields") List<String> fields, @QueryParam("ids") List<String> ids) {
 List<UserSettings> responseArr = mailerService.fetchSettings(ids,fields);
return Response.ok(responseArr).build();
}

When I make a GET request on the URL http://localhost:8181/settings?ids=123&fields=customData,user_id I get the following:

[
{
    "id": 0,
    "user_id": 123,
    "customData": "testCustomDataFor123",
    "deactivationDate": null
}
]

While what I want is :

[
{
    "user_id": 123,
    "customData": "testCustomDataFor123"
}
]
frigocat
  • 283
  • 2
  • 13
  • Possible duplicate of [this question](https://stackoverflow.com/questions/23101260/ignore-fields-from-java-object-dynamically-while-sending-as-json-from-spring-mvc). – Andrew S Jan 03 '18 at 18:14

3 Answers3

3

Put @JsonIgnore at the fields you don't want or its getter.

Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42
1

Using the annotation @JsonIgnore is a solution if you can decide on the attributes to be filtered at compile-time. In your example you want to filter at run-time, which can be achieved using techniques from your JSON library. For example, when using Genson you could do something like this:

new GensonBuilder().exclude("password").create();

However, by doing so you loose the advantage of not having to care about how your response is serialised into JSON. Therefore, I would like to suggest that you think if it is really necessary that clients can dynamically decide on the attributes to be returned. Another solution might be to use media-types other than application/json that would allow the client to request different views of the resource. Jersey distributes incoming requests using the media-type given in the Accept header to the methods in the service class. In each method you can then work with different sub-classes of your UserSettings class that exclude different attributes using the annotation @JsonIgnore.

braunpet
  • 449
  • 1
  • 7
  • 18
0

You could do it how the other responses suggests. Another option with JAX-RS would be to leverage another Genson feature that enables you to filter what properties should be included or excluded. To do so register a custom Genson instance with this special Filter.

UrlQueryParamFilter filter = new UrlQueryParamFilter();
Genson genson = new GensonBuilder().useRuntimePropertyFilter(filter).create();
new ResourceConfig()
  .register(new GensonJaxRSFeature().use(genson))
  .register(filter);

And then in the query define the properties you want to include or exclude like that: http://localhost/foo/bar?filter=age&filter=name.

Some more explanation can be found here.

eugen
  • 5,856
  • 2
  • 29
  • 26