Customize JSON view with Jackson for Dynatable

270 Views Asked by At

I am working on a Spring Boot application. In the html view, I make a ajax call to a RestController, which returns a list of custom entities:

@Controller
public class MyController {
    @ResponseBody
    @JsonView(View.MyView.class)
    public List<CustomEntity> getEntities() {
        ...
    }
}

This is working fine, I am getting, as expected, following structure:

{
    "id": "1",
    "name": "Test1"
},
{
    "id": "2",
    "name": "Test2"
}

In the view, I want to use it with Dynatable. And here comes my problem. I need following structure:

{
  "records": [
    {
      "id": "1",
      "name": "Test1"
    },
    {
      "id": "2",
      "name": "Test2"
    }
  ],
  "queryRecordCount": 2,
  "totalRecordCount": 2
}

Is there a way to generate the JSOn view using jackson (or any other framework) based on a template, so I can use the data with Dynatable, and if so, how?

Thanks in advance,

Stephan

1

There are 1 best solutions below

1
On BEST ANSWER

You could create a wrapper that does this for you...

class DyntableResponse<T> {
  private List<T> records;
  public List<T> getRecords() { return records; }
  public void setRecords(final List<T> records) { this.records = records; }
  public int getQueryRecordCount() { return records.size(); }
  public int getTotalRecordCount() { return records.size(); }
}

And then return it from your RestController...

@Controller
public class MyController {
    @ResponseBody
    @JsonView(View.MyView.class)
    public DyntableResponse<CustomEntity> getEntities() {
       final DyntableResponse<CustomEntity> resp = new DyntableResponse<>();
       resp.setRecords(...); // Your finder here.
       return resp;
    }
}

This is untried, but should be close.