我正在构建一个API,我已经构建了我的资源类,使用JsonViews根据api收到的请求过滤某些字段。我已经正常工作,但现在,我正在尝试进行一些性能升级,其中资源上的某些字段甚至都没有计算。我在想,如果我能以某种方式制作一个条件表达式来评估使用哪个JsonView,这可能是一个起点 - 但是,我不确定这种方法。还有更好的方法吗?
到目前为止我得到了什么:
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;
}
答案 0 :(得分:0)
我在代码中做了类似的事情,只需使用getter而不是直接注释属性。这样,序列化器只会为带注释的字段调用getter。