localdatetime转化为date_将LocalDate和LocalDateTime序列化为Unix时间戳

I'm moving from using java.sql.Timestamp and java.util.GregorianCalendar to employ java.time.* new classes in a Spring MVC application.

So I changed every

private GregorianCalendar field;

to

private LocalDate field;

or

private LocalDateTime field;

But now when serializing those beans, they get serialized like this:

"field": {

"year": 1970,

"month": "JANUARY",

"dayOfMonth": 18,

"dayOfWeek": "SUNDAY",

"era": "CE",

"dayOfYear": 18,

"leapYear": false,

"monthValue": 1,

"chronology": {

"id": "ISO",

"calendarType": "iso8601"

}

},

I found answers to other questions that mention to add a dependency to jackson-datatype-jsr310 and obtained:

"field": [

1970,

1,

18

],

but I still want a unix timestamp when serializing like I got with GregorianCalendar fields: how can I achieve that? Can I avoid a custom serializer (and deserializer)?

These are relevant for resource responses and request bodies (as in POST, PUT, etc), not for request parameters.

The Jackson ObjectMapper is configured like so:

jacksonConverter.getObjectMapper().enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

jacksonConverter.getObjectMapper().disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);

解决方案

In the JavaDoc to JavaTimeModule (included in jackson-datatype-jsr310 library), we can read the following:

Most java.time types are serialized as numbers (integers or decimals as appropriate) if the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS feature is enabled [...]

[...] If SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is disabled, timestamps are written as a whole number of milliseconds. [...]

and then:

Some exceptions to this standard serialization/deserialization rule:

[...]

LocalDate, LocalTime, LocalDateTime, and OffsetTime, which cannot portably be converted to timestamps and are instead represented as arrays when WRITE_DATES_AS_TIMESTAMPS is enabled.

You can indeed see that LocalDateTime cannot be ubiquitously converted to the Unix timestamp because its toEpochSecond method takes ZoneOffset as parameter.

To sum up, it seems the best thing you can do is replacing LocalDateTime with Instant (see this great answer for an explanation of the difference between LocalDateTime and Instant).

Other than that, you would indeed need custom JsonSerializer and JsonDeserializer.

Here's a working code sample:

public static void main(String[] args) throws Exception {

ObjectMapper objectMapper = new ObjectMapper()

.registerModule(new JavaTimeModule())

.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);

Entity entity = new Entity(Instant.now());

StringWriter writer = new StringWriter();

objectMapper.writeValue(writer, entity);

System.out.println(writer.getBuffer());

}

@lombok.Value

static class Entity {

Instant timestamp;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值