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.

2
  • Maybe @JsonIgnore the field and create a getter that unwraps the Optional<String> to String and annotate that getter with @JsonRawValue? E.g. @JsonRawValue getData() { return data.orElse(null); } Commented Nov 25, 2019 at 10:52
  • Having an optional field is not a good idea! Commented Nov 25, 2019 at 10:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.