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"
}
]
将@JsonIgnore
放在您不想要的字段或其 getter 中。
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
.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.