简体   繁体   中英

Spring WebClient filter Null from Json Request

I am using Spring WebClient Api to make a rest api call.

I have an entity object-- JobInfo which acts as my POST Request pay-load.

The below Rest API fails because certain attributes of JobInfo are null.

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();
    }

I need to filter out the Null attributes from sending it across the rest call.

I understand this can be easily achieved by including below annotation on JobInfo class.

@JsonInclude(JsonInclude.Include.NON_NULL) 

But JobInfo is coming from a third party Jar, so I cannot touch this class.

Is there a way I can configure this in webClient to filter this out or any other option?

Try with this:

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM