Reputation: 65
I have a Java web service with a Jersey REST endpoint that returns a list of Restaurant POJOs as JSON objects (see Restaurant class below). The endpoint looks like this
/api/restaurants
and returns all the data tied to the Restaurant class. However, I want to add another, more lean endpoint that looks like this
/api/restaurants/name
which returns only the id
and name
of the Restaurant POJO for all restaurants. Is there a nice way to do this in Jersey out of the box (e.g. specify the fields you want from a POJO for specific endpoints)?
The corresponding POJO looks something like this:
@XmlRootElement
public class Restaurant {
// Members
private Long id;
private String name;
private List<Menu> menus;
...
// Constructors
public Restaurant() {}
...
// Getters and setters
...
}
If you need anything else, please don't hesitate to let me know! Thanks!
Upvotes: 1
Views: 3193
Reputation: 2096
Yes, Jersey has support for selecting the elements that are included in serialized XML/JSON. Take a look at the entity filtering section of the manual.
Essentially, you annotate particular @XmlElements in your POJO with custom annotations. In your REST resource, you pass the annotation to Jersey when you build the Response.
Note that this only works if you use EclipseLink MOXy as your JAXB provider.
Upvotes: 1
Reputation: 2987
First of all, I am guessing that your api is going to be
/api/restaurants/{restaurantId}/name
and not
/api/restaurants/name
And in regards to your question of jersey having this feature out the box, I am not certain about it. Although, this is a much easier way to handle this.
Inside your POJO you can do something like this:
public class Restaurant {
// Members
private Long id;
private String name;
private List<Menu> menus;
...
// Constructors
public Restaurant() {}
...
// Getters and setters
...
// For getting only id and name
public Map getIdAndName()
{
Map<Object, Object> map = new HashMap<>();
map.put("id", this.id);
map.put("name", this.name);
return map;
}
// For getting just a list of menu and name
public Map getNameAndMenu()
{
Map<Object, Object> map = new HashMap<>();
map.put("menus", this.menus);
map.put("name", this.name);
return map;
}
And in your service class you can pretty much use something like this
@Path("/api/restaurants/{restaurantId}/name")
@Produces("application/json")
public String getRestaurantName(@PathParam("restaurantId") String restaurantId)
{
// GET RESTAURANT
Restaurant restaurant = getRestaurant(restaurantId);
Gson gson = new Gson();
// CONVERT TO JSON AND RETURN (or let jersey do that serializable, whichever way is preferable to you.
return gson.toJson(restaurant.getIdAndName());
}
Hope this helps!
Upvotes: 0