首页 > 解决方案 > Swagger 2.8.0 无法生成 api-docs

问题描述

当我调用 swagger/v2/api-docs端点时,我无法在我的 Spring Boot 应用程序中获得有效的 json。

铬错误信息:

此页面包含以下错误: 第 1 行第 1330 列的错误:xmlParseEntityRef: no name 下面是页面的呈现直到第一个错误。

使用开发人员工具,我看到 swagger.json 包装在 xml 标记中,内容类型也设置为 application/xhtml+xml。响应如下所示:

<Json>{"swagger":"2.0",..............</Json>

我正在使用Spring Boot 2.0.0.RELEASESpring 5.0.4.RELEASE并为 XML 映射jackson-dataformat-xml依赖版本2.9.4

有没有一种方法可以application/json作为内容类型发送或配置杰克逊依赖项,弹簧将其加载为类路径中的第一个?或者有没有其他方法可以解决?

对于杰克逊,我们只使用了导入,没有单独的配置。

招摇配置:

@SpringBootApplication (exclude = {SecurityAutoConfiguration.class})
public class Main {

public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
}

@ConditionalOnWebApplication
@EnableSwagger2
public static class SwaggerConfig {

    @Bean
    public Docket springfoxDocket() {

        StringVendorExtension vendorExtension = new StringVendorExtension("x-wso2-security", Wso2Config.serialize());
        List<VendorExtension> vendorExtensions = new ArrayList<>();
        vendorExtensions.add(vendorExtension);

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))
                .build()
                .protocols(protocolSet())
                .apiInfo(apiInfo())
                .extensions(vendorExtensions)
                .directModelSubstitute(LocalDateTime.class, Date.class)
                .useDefaultResponseMessages(false).enableUrlTemplating(false)
                ;
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "Event",
                "Creates, deletes, reads events",
                "2.0",
                "",
                null,
                null, null, Collections.emptyList());
    }

    private Set<String> protocolSet() {
        Set<String> protocolsSet = new HashSet<>();
        protocolsSet.add("http");
        protocolsSet.add("https");
        return protocolsSet;
    }

}
}

标签: javaspringswagger-2.0jackson-dataformat-xml

解决方案


由于您有jackson-dataformat-xml依赖项,spring boot 会将内容类型默认为application/xml. 如果您想application\json作为内容类型,请配置restTemplate为这样做。请按照问题 Swagger 2 接受 xml 而不是 json


推荐阅读