nik*_*sfi 3 java spring json jackson spring-boot
我正在使用 spring-boot 2.5.4 并尝试进行default-property-inclusion=non_null
全局设置,以便 null 值不再出现在我的 spring web 服务器的响应中。
我已经按照前面的问题spring.jackson.default-property-inclusion=non_null
中的描述在我的项目中进行了配置。application.yml
spring:
jackson:
default-property-inclusion: non_null
Run Code Online (Sandbox Code Playgroud)
不幸的是,空值仍然包含在我的控制器的输出中:
{
"enabled": true,
"name": "foo",
"subdomain": null,
"tenantId": null
}
Run Code Online (Sandbox Code Playgroud)
然而,如果我直接将非空添加到我的 dto 中,有效的方法是:
@Data
@NoArgsConstructor
@JsonInclude(Include.NON_NULL)
public class GlobalTenantGet {
private UUID tenantId;
private String name;
private String subdomain;
private boolean enabled;
}
Run Code Online (Sandbox Code Playgroud)
屈服
{
"enabled": true,
"name": "foo"
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样。
为什么@JsonInclude
在 dto 上本地配置会导致 null 属性按预期消失,但为什么配置却spring.jackson.default-property-inclusion=non_null
没有相同的效果?
在中设置断点org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration.JacksonObjectMapperConfiguration#jacksonObjectMapper
表明,中配置的属性application.yaml
确实成功实现了杰克逊:
ObjectMapper
控制器中的自动接线ObjectMapper
在控制器中自动装配并直接通过 序列化我的对象时,我得到了预期的行为objectMapper.writeValueAsString()
。
ObjectMapper
这些主要是为了回复Pawel Woroniecki的回答
我有一个
@Configuration
public class ObjectMapperConfiguration {
@Primary
@Bean
public ObjectMapper objectMapper() {
final var om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_NULL);
return om;
}
}
Run Code Online (Sandbox Code Playgroud)
输出中仍包含 null 属性
Jackson2ObjectMapperBuilder
与serializationInclusion
@Configuration
public class ObjectMapperConfiguration {
@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
return new Jackson2ObjectMapperBuilder().serializationInclusion(JsonInclude.Include.NON_NULL);
}
}
Run Code Online (Sandbox Code Playgroud)
仍然产生
{
"enabled": true,
"name": "foo",
"subdomain": null,
"tenantId": null
}
Run Code Online (Sandbox Code Playgroud)
MappingJackson2HttpMessageConverter
{
"enabled": true,
"name": "foo",
"subdomain": null,
"tenantId": null
}
Run Code Online (Sandbox Code Playgroud)
仍然没有布埃诺:-(
看来@EnableWebMvc
罪魁祸首就是它。我有一个WebMvcConfigurer
看起来像这样的:
@Configuration
@EnableWebMvc // <----- this is the culprit!
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
.allowedOrigins("example.com")
.allowedHeaders("*");
}
@Bean
public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
public InternalResourceViewResolver defaultViewResolver() {
return new InternalResourceViewResolver();
}
}
Run Code Online (Sandbox Code Playgroud)
注释掉@EnableWebMvc
可以让一切按预期工作。
归档时间: |
|
查看次数: |
3975 次 |
最近记录: |