4

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
}
samxiao
  • 2,587
  • 5
  • 38
  • 59

0 Answers0