所有配置 DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES 均无效

With all configurations DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES not working

我尝试了以下 SO 线程中提供的所有解决方案:

Jackson FAIL_ON_UNKNOWN_PROPERTIES to false not working

jackson Unrecognized field

Spring Boot Web- Set FAIL_ON_UNKNOWN_PROPERTIES to false in Jackson

还有大约 10 个类似的 SO 线程。

这是我的 Spring 启动应用程序:

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {

    @Autowired
    private WebClient webClient;

    public static void main(String args[]) {
        SpringApplication.run(MyApplication.class, args);

    }

    @Bean
    public CommandLineRunner demo() {
        return (args) -> {
            getDetails("abcd12345");

        };
    }

    private void getDetails(String nodeId) throws IOException {
        Mono<String> mono = webClient.get().uri("/end/point").retrieve().bodyToMono(String.class);
        System.out.println(mono.block());
        final ObjectNode node = objectMapper().readValue(mono.block(), ObjectNode.class);
        System.out.println(node.get("parent").get("properties").get("nonExisting:keyhere").asText());  // NPE here
    }

    @Bean
    public ObjectMapper objectMapper() {
        return Jackson2ObjectMapperBuilder.json().featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .build();
    }

    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.failOnUnknownProperties(false);
        return builder;
    }

}

我的 application.properties 文件有:

spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=false

输出:

Caused by: java.lang.NullPointerException: null
    at com.springbatch.parallel.processing.Application.getDetails(MyApplication .java:43)

但我仍然收到不存在密钥的 NullPointerException (NPE)。我正在尝试禁用 FAIL_ON_UNKNOWN_PROPERTIES。我在这里缺少什么?

您将需要处理 null 被链式方法调用中的任何调用返回的可能性,如下所示:

private void getDetails(String nodeId) throws IOException {
    Mono<String> mono = webClient.get().uri("/end/point").retrieve().bodyToMono(String.class);
    System.out.println(mono.block());
    final ObjectNode node = objectMapper().readValue(mono.block(), ObjectNode.class);
    JsonNode parentNode = node.get("parent");
    if (parentNode != null) {
        JsonNode parentPropertiesNode = parentNode.get("properties");
        if (parentPropertiesNode != null) {
            JsonNode nonExistingKeyNode = parentPropertiesNode.get("nonExisting:keyhere");
            if (nonExistingKeyNode != null) {
                System.out.println(nonExistingKeyNode.asText());
            }
        }
    }
}

此外,不惜一切代价避免在 Reactive 堆栈中使用 block()。通过这样做,您正在浪费使用 Spring WebFlux 的所有好处。这是一个非常有趣的在线资源,关于使用 Reactive 堆栈时的常见错误:https://medium.com/javarevisited/five-mistakes-to-avoid-in-reactive-java-786927ffd2f6.