public static void main(String[] args) {
TestDate testDate = new TestDate();
testDate.setTime(LocalDateTime.of(1970,1,2,8,0,1));
String s = JSONUtil.toJsonStr(testDate);
System.out.println("s="+s);
TestDate testDate1 = JSONUtil.toBean(s, TestDate.class);
System.out.println(testDate1);
}
s={"time":86401000}
TestDate{time=8640-09-30T00:00}
用JSONUtil.toJsonStr()把Bean转成Json字符串后,再用JSONUtil.toBean()把带时间戳的json字符串转换成Bean时,如果时间戳小于等于2147483647(即Integer最大值),转换就会出错。查询源码后发现了原因。
LocalDateTime类型使用TemporalAccessorConverter转换器。只有当时间戳大于2147483647(即为Long类型),才会把value当成时间戳,否则会转成字符串。若value是八位数的则当成YYYYMMDD格式转换,所以有上面的结果。
解决方法:
- 使用JSONConfig设置dateFormat指定格式
- 更新到最新版本
public static void main(String[] args) {
TestDate testDate = new TestDate();
testDate.setTime(LocalDateTime.of(1970,1,2,8,0,1));
JSONConfig jsonConfig = JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss");
JSONObject object = new JSONObject(testDate, jsonConfig);
String s = JSONUtil.toJsonStr(object);
System.out.println(s);
JSONObject object1 = new JSONObject(s, jsonConfig);
TestDate testDate1 = JSONUtil.toBean(object1, TestDate.class);
System.out.println(testDate1);
}
{"time":"1970-01-02 08:00:01"}
TestDate{time=1970-01-02T08:00:01}