Skip to content

Cached Optional serializer does not apply annotations for POJO properties #17

@codicusmaximus

Description

@codicusmaximus

Simple test case:

public class JsonObjectTest {
    
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
    private Optional<Date> date1;
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM")
    private Optional<Date> date2;
    
    public JsonObjectTest () {}

    public Optional<Date> getDate1() {
        return date1;
    }
    public void setDate1(Optional<Date> date1) {
        this.date1 = date1;
    }
    public Optional<Date> getDate2() {
        return date2;
    }
    public void setDate2(Optional<Date> date2) {
        this.date2 = date2;
    }
    
}
public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        JsonObjectTest t = new JsonObjectTest();
        t.setDate1(Optional.ofNullable(new Date()));
        t.setDate2(Optional.ofNullable(new Date()));
        ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());
        System.out.println(mapper.writeValueAsString(t));
    }
}

produces the output:
{"date1":"2017-03-10","date2":"2017-03-10"}

changing the order of the members to:

    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM")
    private Optional<Date> date2;
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
    private Optional<Date> date1;

produces the output:
{"date2":"2017-03","date1":"2017-03"}

I have found that the issue lies in OptionalSerializer.java on the ser = _findCachedSerializer(provider, value.getClass()); line. The first time a Date is encountered, a new serializer is constructed which observes the relevant annotation; however, every time a Date is encountered afterwards the cached serializer is used without any consideration regarding annotation differences.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions