Добавить @JsonInclude(JsonInclude.Include.USE_DEFAULTS)
аннотацию к вашему классу.
@JsonInclude(JsonInclude.Include.USE_DEFAULTS)
class RequestVO {
String optional;
public RequestVO(String optional) {
this.optional = optional;
}
public String getOptional() {
return optional;
}
public void setOptional(String optional) {
this.optional = optional;
}
}
Пример:
RequestVO requestVO = new RequestVO(null);
ObjectMapper mapper = new ObjectMapper();
try {
String requestString = mapper.writeValueAsString(requestVO);
System.out.println(requestString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Вывод:
{"optional":null}
Со значением:
RequestVO requestVO = new RequestVO("test");
ObjectMapper mapper = new ObjectMapper();
try {
String requestString = mapper.writeValueAsString(requestVO);
System.out.println(requestString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Вывод:
{"optional":"test"}
Вы можете использовать аннотацию @JsonInclude
для четных свойств.Таким образом, вы можете сериализовать как null или игнорировать некоторые свойства при сериализации.