I am using Jersey framework to create a Rest API. The API creates an account for a rider and driver for sharing a ride application. Here, are the dependencies for my project.
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
</dependencies>
I am having a problem serializing the Java Object "User" (that contains all the information about the rides posted by a driver) to JSON object because I only want specific attributes to be converted back to JSON. Here are my "User" class attributes:
private String first_name;
private String last_name;
private String phone;
private String picture;
private boolean is_active;
private int aid;
private List<Rating> drivers_rating;
private List<Rating> riders_rating;
But, when I do a GET request to get Drivers rating, I only want the JSON response to contain "first_name, phone, and drivers_rating". Here is what I have tried:
@Path("{aid}/driver")
@GET
@Produces(MediaType.APPLICATION_JSON)
public User viewDriverRatings(@PathParam("aid") int aid) {
return repo.viewDriverRatings(aid);
}
But, that returns the JSON response with all the attributes. What should I do to only return specific attributes into JSON?
If you do need to restrict columns. The various options for you. 1. Create another class for this restricted visibility, containing "first_name, phone, and drivers_rating". This would be better in terms of design. 2. Can use transient. This would not be good design, as this would forbid the entire class object to be serialized with these properties for any other feature too.
I wouldnt recommend to restrict in JSON level. That would be a bad design.