可选查询字符串枚举参数-openapi,springboot

时间:2019-08-23 16:50:52

标签: spring-boot spring-mvc swagger openapi

我有一个OpenApi规范:

paths:
  /lessons:
    get:
      tags:
        - lesson
      operationId: getLessons
      parameters:
        - in: query
          name: daysOfWeek
          schema:
            type: array
            items:
              $ref: '#/components/schemas/DaysOfWeekEnum'

使用swagger代码生成这样的端点,例如:

 @ApiOperation(value = "Get a collection lessons", nickname = "getLessons", notes = "", response = LessonDto.class, responseContainer = "List", tags={ "lesson", })
    @ApiResponses(value = { 
        @ApiResponse(code = 200, message = "List of Lessons", response = LessonDto.class, responseContainer = "List") })
    @RequestMapping(value = "/lessons",
        produces = { "application/json" }, 
        method = RequestMethod.GET)
    default ResponseEntity<List<LessonDto>> _getLessons(@ApiParam(removed for brevity) @Valid @RequestParam(value = "daysOfWeek", required = false, defaultValue="new ArrayList<>()") List<DaysOfWeekEnum> daysOfWeek) {
        return getLessons(daysOfWeek);
    }

我在如下测试中使用 TestRestTemplate

ResponseEntity<List<LessonDto>> lessonDtos =
        testRestTemplate.exchange("/lessons", HttpMethod.GET, null,
            new ParameterizedTypeReference<List<LessonDto>>() {
            });

此网址有效:

/lessons?daysOfWeek=THURSDAY

这些网址不:

/lessons
/lessons?daysOfWeek=SOME_INVALID_VALUE

...我得到以下错误:

  

嵌套的例外是   com.fasterxml.jackson.databind.exc.MismatchedInputException:无法   在START_OBJECT中反序列化java.util.ArrayList的实例   令牌

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

为了给您一个empty list,您需要将默认值设置为空字符串:

@RequestParam(value = "daysOfWeek", 
              required = false, 
              defaultValue = "") List<DaysOfWeekEnum> daysOfWeek) 

答案 1 :(得分:0)

因此,该问题与openapi-generator bug有关。摘要为:

  

将数组类型的参数添加到操作时,将生成   Spring代码在Spring MVC中包含无效的defaultValue   参数注释

解决方法是升级到openapi-generator的更高版本-4.0.0对我有用。

顺便说一句,错误消息:

  

例外是   com.fasterxml.jackson.databind.exc.MismatchedInputException:无法   从START_OBJECT令牌中反序列化java.util.ArrayList实例

..有点红鲱鱼,实际上与TestRestTemplate有关,即ParameterizedTypeReference部分。将其更改为String.class即可确定错误的真实性质。