【问题标题】:Spring WebClient filter Null from Json RequestSpring WebClient 从 Json 请求中过滤 Null
【发布时间】:2020-04-25 11:28:21
【问题描述】:

我正在使用 Spring WebClient Api 进行 rest api 调用。

我有一个实体对象--JobInfo,它充当我的 POST 请求负载。

以下 Rest API 失败,因为 JobInfo 的某些属性为空。

private BatchInfo createBulkUploadJob(JobInfo jobInfo) {
        return webClient.post()
                .uri(URL.concat("/services/data/v47.0/jobs/ingest/"))
                .contentType(MediaType.APPLICATION_JSON)
                .header("Authorization", "OAuth " + TOKEN)
                .bodyValue(jobInfo)
                .retrieve()
                .bodyToMono(BatchInfo.class)
                .block();
    }

我需要过滤掉 Null 属性,以便在其余调用中发送它。

我知道这可以通过在 JobInfo 类中包含以下注释来轻松实现。

@JsonInclude(JsonInclude.Include.NON_NULL) 

但是 JobInfo 来自第三方 Jar,所以我不能碰这个类。

有没有办法可以在 webClient 中配置它以过滤掉它或任何其他选项?

【问题讨论】:

标签: java spring spring-boot spring-mvc


【解决方案1】:

试试这个:

private BatchInfo createBulkUploadJob(JobInfo jobInfo) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ExchangeStrategies strategies = ExchangeStrategies
                .builder()
                .codecs(clientDefaultCodecsConfigurer -> {
                    clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON));
                    clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON));

                }).build();

        WebClient webClient = WebClient.builder().exchangeStrategies(strategies).build();
        return webClient.post()
                .uri(URL.concat("/services/data/v47.0/jobs/ingest/"))
                .contentType(MediaType.APPLICATION_JSON)
                .header("Authorization", "OAuth " + TOKEN)
                .bodyValue(jobInfo)
                .retrieve()
                .bodyToMono(BatchInfo.class)
                .block();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-13
    • 2020-05-04
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2019-06-24
    • 2021-10-26
    相关资源
    最近更新 更多