0

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!

3
  • Are you just missing the AllModels wrapper? You should be getting the array of objects with the field names by default. Commented Dec 14, 2020 at 18:09
  • 1
    He wants to avoid using a wrapper class and asks if a better alternative exist Commented Dec 14, 2020 at 18:11
  • may be create a hashmap Commented Dec 14, 2020 at 18:13

1 Answer 1

1

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);}});
    }
Sign up to request clarification or add additional context in comments.

3 Comments

"AllModels" key will not be available then
@Panagiwths Mpougioukos Well, then I guess you can create a hashmap within that. I have updated the code in soultion accordingly
This was exactly what I was looking for, to modify response body on the go!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.