Skip to content

Optional.empty() not excluded if property declared with type Object #1256

@jearton

Description

@jearton

Jackson version is 2.6.6
Here is the code:

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
        mapper.registerModule(new Jdk8Module());

        JsonResult result = new JsonResult();
        result.setA(Optional.empty());
        result.setB(Optional.empty());
        System.out.println(mapper.writeValueAsString(result));
@Data
public class JsonResult {
    private Object a;
    private Optional<Object> b;
}

Then I got the output: {"a":null}

The real value of both is the same, why the results are different?

How can I avoid null in such case?

By the way, I tried 'NON_EMPTY'. It can work, but it also ignores zero and empty array. I want to keep them.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions