Jackson converting java object primitive properties as optional in json string

Cugomastik :

I am new in Spring Boot and I would like to send a request to a 3rd party API. I have the below post parameters in JSON to be used as the @RequestBody;

{ "startDate" : "2015-07-01", "endDate" : "2015-10-01", "userId" : 1, "type" : 1, }

OR

{ "startDate" : "2015-07-01", "endDate" : "2015-10-01" }

public class ReportRequest {

@NotNull
private String startDate;

@NotNull
private String endDate;

private int userId;

private int type;

//getters and setters

I used @JsonInclude(JsonInclude.Include.NON_EMPTY on the class and field level. I also tried NON_NULL to ignore the 'userId' and 'type' but I still have them in the @RequestBody object.

@PostMapping(value="/getData", produces = "application/json")
public ResponseEntity getReport(@Valid @RequestBody ReportRequest reportRequest){

There is no problem when I send the request with all the JSON properties. However, when I just send the mandatory data, the 'userId' and the 'type' are automatically set to 0.

I know using the Optional is not the best practice. I could not figure out a way of creating the request Object with the 2 optional JSON request data. Thanks.

Deadpool :

The userId and type are of int which is primitive and default value is 0 and JsonInclude.Include.NON_NULL will only ignore properties with null values, so make userId and type as Integer type so that it's default value is null and jackson can exclude them

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReportRequest {

  @NotNull
  private String startDate;

  @NotNull
  private String endDate;

  private Integer userId;

  private Integer type;

 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3651&siteId=1