Search code examples
springspring-boothttpdto

How to change spring resources list name


I have a controller returning all cars in my database. It is achieved by putting the car list into Resources(see the code). I want to be able to rename the list's name from 'carDTOList' to 'carList". How to do that?

public class CarDTO {

    private String id;
    private UserDTO owner;
    private String brand;
    private String model;
    private String color;
    private String plate;
    private String additionals;

@GetMapping("/cars")
public ResponseEntity<?> getAllCars() {
    List<Resource<CarDTO>> cars = StreamSupport.stream(repository.findAll().spliterator(), false)
            .map(car -> assembler.toResource(modelMapper.map(car, CarDTO.class)))
            .collect(Collectors.toList());

    Resources<Resource<CarDTO>> carsResource = new Resources<Resource<CarDTO>>(cars, ControllerLinkBuilder
            .linkTo(ControllerLinkBuilder.methodOn(CarController.class).getAllCars()).withSelfRel());

    return ResponseEntity.ok(carsResource);
}

{ "_embedded": { "carDTOList": [ { "id": "5d5bc8144a8fb83fd42120e1", "owner": { "id": "5d5bc8144a8fb83fd42120de",


As you see in the response it is set to 'carDTOList'


Solution

  • You can use Spring annotation:

    @org.springframework.hateoas.core.Relation(value = "resource", collectionRelation = "resources")
    

    to annotate your DTO class. So now when you return one element it will be called resource. If you return list it will be called resources.