You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Swagger UI/SpringDoc不编码HTML特殊字符

如何让Swagger UI不对OpenAPI示例中的HTML特殊字符编码(SpringDoc配置方案)

在OpenAPI规范中定义含HTML/XML特殊字符的示例时,Swagger UI会自动对这些字符做HTML编码(比如<转为&lt;,"转为&quot;),导致示例显示不符合预期。比如定义的示例是<bar baz="hello">world</foo>,实际显示成&lt;bar baz=&quot;hello&quot;&gt;world&lt;/foo&gt;,以下是解决方法:

一、SpringDoc配置:关闭Swagger UI的字符编码

通过配置Swagger UI的初始化参数,直接禁用示例的HTML编码。

方式1:配置类实现

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springdoc.core.properties.SwaggerUiConfigParameters;

@Configuration
public class SpringDocConfig {

    @Bean
    public SwaggerUiConfigParameters swaggerUiConfigParameters() {
        SwaggerUiConfigParameters config = new SwaggerUiConfigParameters();
        // 关键配置:关闭示例内容的HTML转义
        config.addInitParameter("escapeHtml", "false");
        return config;
    }
}

方式2:配置文件实现

在application.yml中添加:

springdoc:
  swagger-ui:
    init-parameters:
      escapeHtml: 'false'

或者application.properties:

springdoc.swagger-ui.init-parameters.escapeHtml=false

二、OpenAPI规范层面:正确定义示例格式

如果是XML类型的示例,在YAML中使用**块折叠标量(>)**来保留原始格式,避免YAML解析时自动转义特殊字符。示例如下:

location:
  type: object
  example: >
    <dct:Location>
      <dcat:bbox rdf:datatype="https://www.iana.org/assignments/media-types/application/vnd.geo+json">
          {"type": "LineString", "coordinates": [[1, 2], [3, 4]]}
      </dcat:bbox>
      <locn:geometry rdf:datatype="https://www.iana.org/assignments/media-types/application/vnd.geo+json">
          {"type": "Polygon", "coordinates": [[[5, 6], [7, 8]]]}
      </locn:geometry>
    </dct:Location>

块折叠标量会保留换行和原始字符,不会自动转义<、"等符号,配合SpringDoc的escapeHtml=false配置,就能让Swagger UI正确渲染XML示例。

三、效果验证

配置完成后,Swagger UI中会直接展示原始的XML内容:

<?xml version="1.0" encoding="UTF-8"?>
<abc:Collection>
  <dct:Location>
    <dcat:bbox rdf:datatype="https://www.iana.org/assignments/media-types/application/vnd.geo+json">
        {"type": "LineString", "coordinates": [[1, 2], [3, 4]]}
    </dcat:bbox>
    <locn:geometry rdf:datatype="https://www.iana.org/assignments/media-types/application/vnd.geo+json">
        {"type": "Polygon", "coordinates": [[[5, 6], [7, 8]]]}
    </locn:geometry>
  </dct:Location>
</abc:Collection>

内容的提问来源于stack exchange,提问作者Wang Tang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:15:27