0

I am having a POJO UserRequest.java which has 4 fields in it and my use case is that I need to send this POJO as request object with 3 fields to REST Endpoint-1 and as another request object with 4 fields to REST Endpoint-2 (as this one needs 4 fields as input).

public class UserRequest(){

  private String field1;
  private String field2;
  private String field3;
  private String field4;

}

So I want to use same POJO for both REST Endpoints with 'field4' to be passed only in 2nd Endpoint. I tried using @JSONIgnore annotation over 'field4' but it sends 'field4' as null in 1st Endpoint but 1st Endpoint fails as it does not want 'field4' at all. Please suggest how can I use same POJO for both Endpoints.

Vaibhav Bhardwaj
  • 179
  • 1
  • 1
  • 9
  • 1
    JsonIgnore ignores the field for de-/serialization, you should look into direction: ["json ignore null"](https://stackoverflow.com/q/11757487/592355), ["json ignore unknown"](https://stackoverflow.com/q/5455014/592355) ..and advanced: "json view jackson" – xerx593 May 12 '23 at 20:07

1 Answers1

0

You can declare the fourth field as Optional. This way you can pass it to both endpoints, but don't have to pass field4 for Endpoint-1.

public class UserRequest(){

  private String field1;
  private String field2;
  private String field3;
  private Optional<String> field4;

}

Another option is JsonNullable from the jackson-databind-nullable, but I usually prefer using Optional as it is a standard java type.

public class UserRequest(){

 private String field1;
 private String field2;
 private String field3;
 private JsonNullable<String> field4;

}
elpair
  • 46
  • 4