Reputation: 1516
I have a basic Rest Controller which returns a list of models in json to the client:
@RestController
public class DataControllerREST {
@Autowired
private DataService dataService;
@GetMapping("/data")
public List<Data> getData() {
return dataService.list();
}
}
Which returns data in this format:
[
{
"id": 1,
"name": "data 1",
"description": "description 1",
"active": true,
"img": "path/to/img"
},
// etc ...
]
Thats great for starting, but i thought about returning data of this format:
[
"success": true,
"count": 12,
"data": [
{
"id": 1,
"name": "data 1",
"description": "description 1",
"active": true,
"img": "path/to/img"
},
{
"id": 2,
"name": "data 2",
"description": "description 2",
"active": true,
"img": "path/to/img"
},
]
// etc ...
]
But i am not sure about this issue as i can not return any class as JSON... anybody has suggestions or advices?
Greetings and thanks!
Upvotes: 0
Views: 11833
Reputation: 4657
"as i can not return any class as JSON" - says who?
In fact, that's exactly what you should do. In this case, you will want to create an outer class that contains all of the fields that you want. It would look something like this:
public class DataResponse {
private Boolean success;
private Integer count;
private List<Data> data;
<relevant getters and setters>
}
And your service code would change to something like this:
@GetMapping("/data")
public DataResponse getData() {
List<Data> results = dataService.list();
DataResponse response = new DataResponse ();
response.setSuccess(true);
response.setCount(results.size());
response.setData(results);
return response;
}
Upvotes: 7