Update:
只需添加一个@JsonFormat
上面的日期格式注释Instant
财产。这很容易。
如果您有一个带有以下内容的 ObjectMapperJavaTimeModule
就像下一个:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
如果您的班级有Instant
属性,您应该添加@JsonFormat
注释并放置没有毫秒的日期模式。就像下面这样:
public static class TestDate {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss", timezone = "UTC")
Instant instant;
//getters & setters
}
因此,如果将对象序列化为 Json,它会完美运行:
String json = mapper.writeValueAsString(testDate);
System.out.println(json);
Output
{“即时”:“2016-11-10 06:03:06”}
老答案。我不知道为什么,但它不能正常工作:
你可以使用Jackson2ObjectMapperBuilder
来建造它。
您只需添加所需的日期格式即可。它会像下面这样:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ObjectMapper mapper = Jackson2ObjectMapperBuilder
.json()
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.modules(new JavaTimeModule())
.dateFormat(dateFormat)
.build();