1

I have an optional String and would like Jackson to serialize using @JsonRawValue, but the String value is appended with Optional[]. How do I avoid this?

 @JsonRawValue
 Optional<String> data;

I have registered the ObjectMapper with Jdk8Module.

user2761431
  • 925
  • 2
  • 11
  • 26
  • Maybe `@JsonIgnore` the field and create a getter that unwraps the `Optional` to `String` and annotate that getter with `@JsonRawValue`? E.g. `@JsonRawValue getData() { return data.orElse(null); }` – sfiss Nov 25 '19 at 10:52
  • Having an _optional field_ is [not a good idea](https://stackoverflow.com/questions/23454952/uses-for-optional)! – Seelenvirtuose Nov 25 '19 at 10:55

1 Answers1

2

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.

sfiss
  • 2,119
  • 13
  • 19