0

当我引入自定义消息转换器时出现以下 Swagger 错误

Unable to render this definition
The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).

该错误具有误导性,我猜它与转换器混淆了。有什么想法可以解决吗?

我跟着 - swagger-ui 不使用自定义 XML ObjectMapper(不走运)

背景:

我通过 xjc 从 xsd(s) 生成了 pojo。我有一个休息端点,需要同时支持 xml 和 json 的请求/响应

我们通过以下 [spring 文档][1] 部分使其工作:22.16.12 消息转换器

这是我在 MyConfig 中添加的

    @Configuration 
    @EnableWebMvc 
    public class MyConfig implements WebMvcConfigurer {
      @Override
      public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper()));
      }

      @Bean
      @Primary
      public ObjectMapper objectMapper() {
        return new Jackson2ObjectMapperBuilder()
                .modulesToInstall(new JaxbAnnotationModule())
                .build();
      }

      @Bean
      public XmlMapper xmlMapper() {
        return new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .defaultUseWrapper(false)
                .serializationInclusion(JsonInclude.Include.NON_EMPTY)
                .modulesToInstall(new JaxbAnnotationModule())
                .createXmlMapper(true)
                .build();
      } 
    }

和我的控制器

// all the open api annotations //
@RequestMapping(value = "/run",
        produces = {"application/json", "application/xml"},
        consumes = {"application/json", "application/xml"},
        method = RequestMethod.POST)
public ResponseEntity<MyResponse> run(@RequestBody MyRequest request) {
4

1 回答 1

0

好的,关于哪个objectMapper。我不得不清理并删除“@primary”,这在 MyConfig 中起到了作用

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        return new MappingJackson2HttpMessageConverter(new Jackson2ObjectMapperBuilder()
                .modulesToInstall(new JaxbAnnotationModule())
                .build());
    }

    @Bean
    public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter() {
        return new MappingJackson2XmlHttpMessageConverter(new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .defaultUseWrapper(false)
                .serializationInclusion(JsonInclude.Include.NON_EMPTY)
                .modulesToInstall(new JaxbAnnotationModule())
                .createXmlMapper(true)
                .build());
    }
于 2021-02-22T23:55:04.693 回答