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
相关产品推荐
相关产品推荐

