fastjson LocalDateTime parsing fails with parameterized constructors

wr98u20j  于 2021-11-27  发布在  Java
关注(0)|答案(0)|浏览(222)

Repro:
Here is a simple Event class that has a property event_time and a format specified

public class Event {
    @JSONField(name = "event_time", format = "yyyy-MM-dd HH:mm:ss.SSSSSS")
    private final LocalDateTime eventTime;

    public IdentificationEvent(String eventTime) {
        this.eventTime = eventTime;
    }

    public LocalDateTime getEventTime() {
        return eventTime;
    }
}

Here is a simple test that validates if the deserialization works as expected

@Test
    public void testIdentifyEvent() {
        var str = "{\"event_time\": \"2021-11-23 22:42:49.426000\"}";
        var obj = JSON.parseObject(str, Event.class);
        Assert.assertTrue(obj.getEventTime().getYear() == 2021);
    }

Fails with the following error: Text '2021-11-23 22:42:49.426000' could not be parsed at index 10

Fix:
Remove parameterized constructor and use getters and setters

public class Event {
    @JSONField(name = "event_time", format = "yyyy-MM-dd HH:mm:ss.SSSSSS")
    private LocalDateTime eventTime;

    public LocalDateTime getEventTime() {
        return eventTime;
    }

    public void setEventTime(LocalDateTime eventTime) {
        this.eventTime = eventTime;
    }
}

The test now passes.

With parameterized constructors, the format attribute doesn't seem to be enforced.

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题