alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

LocalDateTime parsing fails with parameterized constructors #3956

Open izaaz opened 2 years ago

izaaz commented 2 years ago

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.

github-ganyu commented 2 years ago

I submitted a PR to solve this problem: https://github.com/alibaba/fastjson/pull/3966