How do I use Jackson JSON mapper with Java 8 LocalDateTime?
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple t
If you can't use jackson-modules-java8
for whatever reasons you can (de-)serialize the instant field as long
using @JsonIgnore
and @JsonGetter
& @JsonSetter
:
public class MyBean {
private Instant time = Instant.now();
@JsonIgnore
public Instant getTime() {
return this.time;
}
public void setTime(Instant time) {
this.time = time;
}
@JsonGetter
private long getEpochTime() {
return this.time.toEpochMilli();
}
@JsonSetter
private void setEpochTime(long time) {
this.time = Instant.ofEpochMilli(time);
}
}
Example:
@Test
public void testJsonTime() throws Exception {
String json = new ObjectMapper().writeValueAsString(new MyBean());
System.out.println(json);
MyBean myBean = new ObjectMapper().readValue(json, MyBean.class);
System.out.println(myBean.getTime());
}
yields
{"epochTime":1506432517242}
2017-09-26T13:28:37.242Z