As by my comment, you could ignore the Optional
field and instead use a custom getter for the String
value:
public static class Test {
@JsonIgnore
Optional<String> data;
@JsonRawValue
public String getDataValue() {
return data.orElse(null);
}
public Optional<String> getData() {
return data;
}
public void setData(final Optional<String> data) {
this.data = data;
}
}
public static void main(final String[] args) throws JsonProcessingException {
final ObjectMapper om = new ObjectMapper();
final Test data = new Test();
data.data = Optional.of("Hello World");
final String value = om.writeValueAsString(data);
System.out.println(value);
}
Note: Jdk8Module is included by default in this jackson version. However, using @JsonRawValue seems to override the serialization of Optional, so a custom getter that gets rid of the Optional helps with that.