Morteza Asadi Morteza Asadi - 13 days ago 6
Java Question

Is there any way to put @JsonView on Controller method with QueryResult returnType?

I have an

ViewModel
and put
json
annotation on some fields according this post of spring.io like below:

public class SurveyViewModel{
@JsonView(View.Summary.class)
private Long id;
@JsonView(View.Summary.class)
private String title;
private String description;
private String endDate;
//Here is getters & setters
}


When I retrieve data from my
REST Controller
, if return Type of my method is
List
, json-result is OK:

@RequestMapping(value = "/getAllGrid", method = RequestMethod.GET)
@JsonView(View.Summary.class)
@ResponseBody
public List<SurveyViewModel> getAll{
return ModelMapper.mapList(iSurveyService.getAll(), SurveyViewModel.class);
}


But when I apply paging on my result & change return type of this method to
QueryResult
, json-result is empty:

@RequestMapping(value = "/getAllGrid", method = RequestMethod.GET)
@JsonView(View.Summary.class)
@ResponseBody
public QueryResult<SurveyViewModel> search(String order, int pageNumber, int pageSize) {
return ModelMapper.mapQueryResult(iSurveyService.getAllGrid(new SearchOption("", order, pageNumber, pageSize)), SurveyViewModel.class);
}


When I apply paging on my result with above method,
pageNumber, totalRecords & pageSize
added to my json result and original-data add to
entityList
as inner json object, Here is my
QueryResult
in json format without apply
@JsonView
:

{
"pageNumber" : 0,
"totalRecords" : 1,
"pageSize" : 10,
"entityList" : [{
"id" : 1,
"title" : "survey1",
"description" : "...",
"endDate" : "2017/01/18",
},{
"id" : 2,
"title" : "survey2",
"description" : "...",
"endDate" : "2016/11/18",
}]
}


Now my question is, Is there any way to put
@JsonView
on Controller method with
QueryResult
returnType?

Answer

QueryResult is an object that I use for pagination, I solve my problem by putting @jsonView on properties of QueryResult class, like below:

public class QueryResult<T> {
    @JsonView(View.Summary.class)
    private int pageNumber;
    @JsonView(View.Summary.class)
    private int totalRecords;
    @JsonView(View.Summary.class)
    private int pageSize;
    @JsonView(View.SummaryWithRecipients.class)
    private List<T> entityList = new ArrayList<T>();
    //Here is getters & setters
}
Comments