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

Kotlin SpringBoot中如何让RestAPI返回JSON格式响应

解决方案

原因分析

当项目引入jackson-dataformat-xml依赖后,Spring MVC的内容协商机制会将XML纳入可选响应格式。升级到Springdoc OpenAPI后,内容协商优先级发生变化,导致默认响应格式变为XML。


方案1:全局配置默认响应为JSON

通过配置Spring MVC内容协商策略,将JSON设为优先格式,同时保留XML支持。

方式1:添加WebMvcConfigurer配置类

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

@Configuration
class WebConfig : WebMvcConfigurer {
    override fun configureContentNegotiation(configurer: ContentNegotiationConfigurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON)
            .mediaType("json", MediaType.APPLICATION_JSON)
            .mediaType("xml", MediaType.APPLICATION_XML)
    }
}

方式2:通过配置文件设置

在application.yml中添加:

spring:
  mvc:
    contentnegotiation:
      default-content-type: application/json
      media-types:
        json: application/json
        xml: application/xml

方案2:统一Controller层默认Produces

在@RestController或@RequestMapping上统一指定默认produces为JSON,需要返回XML的方法单独覆盖配置:

@Tag(description = "ABC details API", name = "abc")
@RestController
@RequestMapping("/api/x1", produces = [MediaType.APPLICATION_JSON_VALUE])
class DetailController(val detailService: DetailService) {

    // 默认返回JSON的接口
    @Operation(summary = "API to fetch details")
    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/product/{productId}", consumes = [MediaType.ALL_VALUE])
    @ApiResponse(responseCode = "200", description = "Ok",
        content = [Content(mediaType = "application/json", schema = Schema(implementation = ProductDetailsResponseDTO::class))])
    fun fetchDetails(@Parameter(name = "productId", required = true)
                     @PathVariable("productId", required = true) productId: Int
    ): ProductDetailsResponseDTO? {
        return productDetailService.fetchDetails(productId)
    }

    // 需要返回XML的接口,单独指定produces
    @GetMapping("/xml/product/{productId}", produces = [MediaType.APPLICATION_XML_VALUE])
    @ApiResponse(responseCode = "200", description = "Ok",
        content = [Content(mediaType = "application/xml", schema = Schema(implementation = ProductDetailsResponseDTO::class))])
    fun fetchDetailsAsXml(@PathVariable("productId") productId: Int): ProductDetailsResponseDTO? {
        return productDetailService.fetchDetails(productId)
    }
}

方案3:统一Springdoc依赖版本

当前你的Springdoc依赖版本不一致(springdoc-openapi-webmvc-core为1.7.0,springdoc-openapi-ui为1.6.12),版本不匹配可能引发未知问题,建议统一为相同版本:

implementation("org.springdoc:springdoc-openapi-webmvc-core:1.7.0")
implementation("org.springdoc:springdoc-openapi-ui:1.7.0")
implementation("org.springdoc:springdoc-openapi-data-rest:1.7.0")
implementation("org.springdoc:springdoc-openapi-kotlin:1.7.0")

内容的提问来源于stack exchange,提问作者Pradeep Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 03:28:30