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

Spring WebFlux集成GraphQL Starter不返回可空字段的解决方案

解决方案

1. 配置Jackson强制包含空字段

在Spring Boot配置文件中添加Jackson序列化规则,让所有字段(包括null值)都被序列化到响应中:

application.yml

spring:
  jackson:
    default-property-inclusion: ALWAYS

application.properties

spring.jackson.default-property-inclusion=ALWAYS

2. 匹配GraphQL Schema字段可空性

在src/main/resources/graphql/schema.graphqls文件中,明确fieldNullable为可空字段(不要加!标记):

type User {
    id: ID!
    email: String
    fieldNullable: String
}

type Query {
    getUser: [User]
}

3. 移除冲突依赖

同时引入spring-boot-starter-web和spring-boot-starter-webflux会引发阻塞式/响应式Web模型的冲突,建议移除spring-boot-starter-web:

<!-- 移除该依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

原理说明

Spring GraphQL默认使用Jackson处理对象序列化,而Jackson默认会过滤掉null值字段,导致响应中缺失fieldNullable。通过设置default-property-inclusion: ALWAYS,强制Jackson序列化所有字段;同时GraphQL Schema的定义要匹配实体类的可空性,确保客户端请求该字段时,服务端允许返回null值并将其包含在响应中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:34:59