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

Content-type Negotiation多配置注册仅首个生效,求技术验证与解决

在Kotlin ContentNegotiation中注册多个自定义转换器的问题解决

你遇到的问题是注册多个自定义ContentNegotiation转换器后仅第一个生效,这通常是因为自定义转换器的canConvert方法没有正确限定处理的ContentType,导致第一个转换器接管了所有JSON类型的请求。

解决步骤:

  1. 检查自定义转换器的canConvert实现
    确保每个转换器只处理对应目标ContentType,避免跨类型匹配:

    • SirenJsonConverter仅在ContentType为Application.SirenJson时返回true
    • ProblemConverter仅在ContentType为Application.ProblemJson时返回true
  2. 修正注册代码
    调整转换器注册逻辑,明确限定每个转换器的处理范围:

    install(ContentNegotiation) {
        register(ContentType.Application.SirenJson, SirenJsonConverter().apply {
            canConvert = { contentType, _ -> contentType == ContentType.Application.SirenJson }
        })
        register(ContentType.Application.ProblemJson, ProblemConverter().apply {
            canConvert = { contentType, _ -> contentType == ContentType.Application.ProblemJson }
        })
        // 默认json转换器处理Application.Json类型
        json()
    }
    

补充说明:

Kotlin ContentNegotiation完全支持同时注册多个自定义转换器,核心是保证每个转换器的职责边界清晰。如果自定义转换器未限定canConvert范围,会优先匹配第一个注册的转换器,导致后续转换器无法触发。

内容的提问来源于stack exchange,提问作者Nicolau Valente

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:39:54