I'm building an API and I've built my resource class to use JsonViews to filter certain fields depending on the request that the api receives. I've got that working properly, but now, I'm trying to pursue some performance upgrades in which certain fields on the resource are not even calculated. I'm thinking if I can somehow make a conditional expression that evaluates which JsonView is being used, that could be a starting point - however, I'm not sure of this approach. Is there a better way?
What I've got so far:
Photo.java:
public class Photo {
@JsonView(Views.Public.class)
private Long id;
...
JsonView(Views.PublicExtended.class)
private Double numLikes;
...
Photo(PhotoEntity entity){
this.id = entity.getId();
...
}
Photo(PhotoEntity entity, OtherObject oo){
this.id = entity.getId();
this.numLikes = oo.getNumLikes();
}
PhotoController.java
@JsonView(Views.Public.class)
@RequestMapping(value = "/user/{user_id}", method = RequestMethod.GET)
public ResponseEntity<List<Photo>> getAllForUser(@PathVariable("user_id") Long userId) throws NotFoundException {
return super.ok(svc.getAllForUser(userId));
}
@JsonView(Views.PublicExtended.class)
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<PhotoResource> getOne(@PathVariable("id") Long id) throws NotFoundException {
return super.ok(svc.getOne(id));
}
PhotoService.java
public Photo entityToResource(PhotoEntity entity) {
// TODO : [Performance] Depending on the view that the controller received, construct the resource with/without OtherObject
String view = "View.PublicExtended.class";
Photo resource;
if(view.equals("View.Public.class")){
resource = new Photo(entity);
}
else{
resource = new Photo(entity, this.getOtherObject(entity));
}
return resource;
}