简体   繁体   中英

fasterxml JsonInclude for optional

I have a dto as the following

public class MyClass {
    @JsonProperty("value")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    public Optional<String> myValue = Optional.empty();
}

When I test serialization

 @Test
    public void should() throws JsonProcessingException {
        //GIVEN
        val myClass = new MyClass();
        myClass.myValue =(Optional.empty());

        //WHEN
        ObjectMapper mapper = new ObjectMapper();
        String valueAsString = mapper.writeValueAsString(myClass);
        System.out.println(valueAsString);
        //THEN

    }

empty optional filed is still serialized

{"value":{"present":false}}

I've tried using Include.NON_ABSENT and user annotation on the whole class - still the filed is serialized.

In some examples I saw that the objectMapper register a jdk8Module. Did you try this? Maybe it only handles the Optional-Instances correct with this module registered.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Jdk8Module());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM