In Java Webclient,, how to completely omitting a field when value is null in Mono serialization

1.1k views Asked by At

I am on Java Spring Boot framework, trying to serialize a Java object using Mono for WebClient to use to send. I want to know whether I can completely remove a field when the value is found null. I don't seem to find a way to do that. Was trying to find an annotation to see whether this works.

Below is an example.

I have a Java class with an object looks like this

public class RequestBody {
  private String name_first;
  private String name_last;
  private String email_address;
}

Using the builder pattern to build it.

RequestBody requestBody =
    RequestBody.builder()
        .name_first(input.getName().getFirst())
        .name_last(input.getName().getLast())
        .build();

Using WebClient + Mono to make a RESTful POST to another API

    return requestBodySpec
      .header("Content-Type", "application/json")
      .body(Mono.just(requestBody), RequestBodyClass)
      .retrieve()
      .bodyToMono(String.class)
      .block();

The JSON result after Mono serialized looks like this.

{
    "name_first": "Foo",
    "name_last": "Bar,
    "email_address": null
}

Expecting to have the request JSON looks like this. And with email_address completely removed when the value is null. How do we do that?

{
    "name_first": "Foo",
    "name_last": "Bar
}
1

There are 1 answers

0
docsa On

Thanks to AI the answer is : Create a Weblux configuration class :

@Configuration
@EnableWebFlux

public class WebFluxConfig implements WebFluxConfigurer {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }

    @Bean
    public Encoder<Object> encoder(ObjectMapper objectMapper) {
        return new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON);
    }
}