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

如何在Swagger UI的v3/api-docs中设置UTF-8编码?

在Swagger v3/api-docs中设置UTF-8编码的解决方案

场景说明

当访问v3/api-docs接口时返回的中文出现乱码,需要确保接口响应的编码为UTF-8,以下是几种常用解决方案(以Spring Boot环境为例):


方法1:通过WebMvcConfigurer配置全局响应编码

创建Web配置类,强制设置默认响应内容类型为UTF-8编码的JSON:

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        // Spring Boot 2.3+ 推荐写法
        configurer.defaultContentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8));
    }
}

如果是旧版本Spring Boot,可以使用已弃用但仍生效的MediaType.APPLICATION_JSON_UTF8替代上述代码中的构造方法。


方法2:通过配置文件全局设置编码

在application.properties中添加:

# 全局HTTP编码配置
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
# Servlet编码配置
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true

或者在application.yml中配置:

spring:
  http:
    encoding:
      force: true
      charset: UTF-8
      enabled: true
server:
  servlet:
    encoding:
      force: true
      charset: UTF-8
      enabled: true

该配置会强制整个应用的HTTP请求和响应都使用UTF-8编码,自然也会覆盖v3/api-docs接口的响应编码。


方法3:针对Swagger OpenAPI配置响应编码

如果只想单独给Swagger的接口设置编码,可以在OpenAPI配置类中指定响应的媒体类型编码:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfiguration {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .components(new Components()
                        // 给全局默认响应设置UTF-8编码
                        .addResponses("default", new ApiResponse()
                                .content(new Content()
                                        .addMediaType("application/json", new MediaType().charset("UTF-8")))));
    }
}

验证方式

访问v3/api-docs接口,查看浏览器开发者工具中响应头的Content-Type字段,若显示为application/json;charset=UTF-8,同时返回的中文内容正常显示,说明配置生效。

内容的提问来源于stack exchange,提问作者Ilya Y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:10:31