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

Spring WebFlux中ServerResponse Jackson序列化问题求助

解决Spring WebFlux GET请求的CodecException问题

嘿,我一眼就瞅出你这段代码的问题啦!你遇到的org.springframework.core.codec.CodecException,根源在于你设置了APPLICATION_JSON的响应类型,但却没给响应体留内容。

问题原因拆解

你写的这段代码:

@GetMapping("/events") 
public Mono<ServerResponse> getEvents() { 
    return ServerResponse.ok() 
        .contentType(APPLICATION_JSON) 
        .build(); 
}

调用build()的时候没有传入任何要返回的内容,但又明确告诉WebFlux要返回JSON格式。这就尴尬了——编码器准备序列化JSON内容,结果啥都没有,自然就抛出异常了。

针对性解决方案

根据你的实际需求,选下面对应的写法就行:

  • 如果要返回空的JSON结构(比如空数组/空对象)
    要是你确实需要返回JSON格式的空内容,得主动传入空的集合或Map:

    import java.util.Collections;
    import org.springframework.http.MediaType;
    
    @GetMapping("/events")
    public Mono<ServerResponse> getEvents() {
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Collections.emptyList()); // 返回空数组,适合列表场景
        // 或者返回空对象:.bodyValue(Collections.emptyMap());
    }
    
  • 如果是忘记添加实际的事件数据
    假设你本来要返回事件列表,得把数据来源(比如事件服务的查询结果)传入body()方法:

    @GetMapping("/events")
    public Mono<ServerResponse> getEvents(EventService eventService) {
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(eventService.findAllEvents(), Event.class); // 传入事件流和类型
    }
    
  • 如果就是要返回无内容的响应
    要是不需要返回任何内容,别用ok(),直接用noContent(),也不用设置JSON类型:

    @GetMapping("/events")
    public Mono<ServerResponse> getEvents() {
        return ServerResponse.noContent().build();
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:24:06