Reputation: 2662
I am new to springboot. My requirement is as below. I have carModel class as below.
@Data
public class CarModel {
private modelName;
private available;
}
Now I have a rest endpoint that returns the list of objects. So the resource looked something like this.
@GetMapping("/models")
public List<CarModel> getModels(){
//Resource Body
}
But this return an array of objects in json, with no field name. But I need the the json , something like this:
{ "AllModels" : [ { "modelName" : "Ferrari", "available" : "Yes"} , {"modelName": "Tesla" , "available" : "Yes"} ]
How can I do this in spring boot? I do know of a solution by defining one more wrapper class with list of CarModel objects in it. But is there any better way of doing it(Something like any annotations, etc.,)
Thanks!
Upvotes: 0
Views: 905
Reputation: 233
You can use ResponseEntity method that is already there available in Spring MVC. Would something like this work for you?
@GetMapping("/models")
public ResponseEntity<List<CarModel>> getCars() {
List<CarModel> carModels = service.methodThatReturnsListOfCarModels();
return ResponseEntity.ok().body(new HashMap<>(){{put("AllModels", carModels);}});
}
Upvotes: 1