我正在构建一个 API,并且我已经构建了我的资源类来使用 JsonViews 根据 api 接收到的请求来过滤某些字段。我已经正常工作了,但是现在,我正在尝试进行一些性能升级,其中甚至没有计算资源上的某些字段。我在想,如果我能以某种方式制作一个评估正在使用哪个 JsonView 的条件表达式,这可能是一个起点 - 但是,我不确定这种方法。有没有更好的办法?
到目前为止我得到了什么:
照片.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;
}