在Spring中返回列表的正确方法是什么

时间:2018-11-23 06:49:55

标签: java spring list data-structures

我写了一个用Spring注释的方法,它将返回一个列表。以下代码片段将代表该方法。

   @RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<ReservationResponse> getAvailableRooms(
            @RequestParam(name = "checkin")
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
            LocalDate checkin,
            @RequestParam(name = "checkout")
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
            LocalDate checkout) {

        return new ResponseEntity<>(new ReservationResponse(), HttpStatus.OK);
    }

我想知道的是,如果我写这是错的吗?

@RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ReservationResponse> getAvailableRooms(
        @RequestParam(name = "checkin")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate checkin,
        @RequestParam(name = "checkout")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate checkout) {
        ResponseEntity<ReservationResponse> reservationResponse = new ResponseEntity<ReservationResponse>();
    return (reservationResponse, HttpStatus.OK);
    }

1 个答案:

答案 0 :(得分:1)

我认为您的 ReservationResponse 包含这样的列表:

class ReservationResponse{
List<Rooms> availableRooms;
}

如果这样,您只需返回 ReservationResponse ,无需添加任何内容。

@RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public ReservationResponse getAvailableRooms(
        @RequestParam(name = "checkin")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate checkin,
        @RequestParam(name = "checkout")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate checkout) {
        ReservationResponse> reservationResponse = new ReservationResponse();
        List<Rooms> rooms = yourService.getAvailableRooms(checkIn,checkOut);
        reservationResponse.setAvailableRooms(rooms);
    return reservationResponse;
    }

或者您可以像这样简单地返回房间

@RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public List<Rooms> getAvailableRooms(
        @RequestParam(name = "checkin")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate checkin,
        @RequestParam(name = "checkout")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate checkout) {

        List<Rooms> rooms = yourService.getAvailableRooms(checkIn,checkOut);

    return rooms;
    }