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

Spring Controller无法处理多种媒体类型问题求助

问题分析与解决方案

问题根源

你的RequestDto是Protobuf生成的Java类,Spring默认的消息转换器无法处理Protobuf对象与JSON格式的互转:

  • 默认的MappingJackson2HttpMessageConverter(负责处理JSON)不支持Protobuf类的序列化/反序列化;
  • 默认的ProtobufHttpMessageConverter仅支持application/x-protobuf媒体类型,不会处理JSON请求。
    即便你在@RequestMapping的consumes里配置了JSON类型,也没有合适的转换器完成请求体解析,因此抛出HttpMediaTypeNotSupportedException。

解决方案

以下两种方式任选其一即可:

方案1:扩展ProtobufHttpMessageConverter支持JSON

  1. 添加依赖
    在Maven pom.xml中引入Protobuf的JSON工具包:

    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java-util</artifactId>
        <version>你的Protobuf版本(如3.24.4)</version>
    </dependency>
    
  2. 配置自定义消息转换器
    创建WebMvc配置类,扩展ProtobufHttpMessageConverter使其支持JSON媒体类型:

    import com.google.protobuf.util.JsonFormat;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.MediaType;
    import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        @Override
        public void configureMessageConverters(java.util.List<org.springframework.http.converter.HttpMessageConverter<?>> converters) {
            ProtobufHttpMessageConverter protoConverter = new ProtobufHttpMessageConverter();
            // 添加JSON媒体类型支持
            protoConverter.addSupportedMediaTypes(MediaType.APPLICATION_JSON);
            protoConverter.addSupportedMediaTypes(MediaType.APPLICATION_JSON_UTF8);
            // 设置JSON解析器,忽略未知字段避免解析报错
            protoConverter.setJsonFormat(JsonFormat.parser().ignoringUnknownFields());
            converters.add(protoConverter);
        }
    }
    

方案2:使用Jackson的Protobuf模块

  1. 添加依赖
    引入Jackson专门处理Protobuf的模块,让默认的JSON转换器支持Protobuf类:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-protobuf</artifactId>
        <version>匹配Spring Boot依赖的Jackson版本(如2.15.3)</version>
    </dependency>
    
  2. 无需额外配置
    Spring Boot会自动检测并注册该模块,MappingJackson2HttpMessageConverter将能直接处理Protobuf类的JSON序列化/反序列化,你的控制器无需修改即可接收JSON请求。

额外注意

你的控制器方法声明返回ResponseDto,但实际返回的是RequestDto实例,这属于代码笔误,建议修正为ResponseDto的构建逻辑,避免后续出现类型转换问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:01:08