我使用以下依赖项使用graphql创建了spring web Flux
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.graphql</groupId>
<artifactId>spring-graphql-test</artifactId>
<scope>test</scope>
</dependency>
和我的 graphql 端点t
@Controller
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@SneakyThrows
@QueryMapping
public Flux<User> getUser() {
return userService.findAllUsers();
}
和用户对象
public class User extends ReusableField implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private String email;
private String fieldNullable;
....
字段 fieldNullable 未从 graphql 响应返回,因此 apollo-garaphql 对于角度显示控制台错误“写入结果时缺少字段 'fieldNullable'”
如何让spring返回这个字段,无论它是否为空
我发现了问题。我有一个 bean 定义
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonConverter.setObjectMapper(mapper);
return jsonConverter;
}
问题出在这一行
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
更改为
mapper.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS);
问题解决了`