我必须通过JMS消息和它的ActiveMQ通信的两个春天启动的应用程序。
一个应用程序发送到其他的应用程序,其包含一个LocalDateTime属性的对象。该目的序列化到JSON,以便被发送到其它的应用程序。
我现在面临的问题是,杰克逊不能当它试图映射传入的JSON我的对象反序列化LocalDateTime属性。该LocalDateTime属性具有以下格式,当它到达了“监听程序”:
"lastSeen":{
"nano":0,
"year":2019,
"monthValue":4,
"dayOfMonth":8,
"hour":15,
"minute":6,
"second":0,
"month":"APRIL",
"dayOfWeek":"MONDAY",
"dayOfYear":98,
"chronology":{
"id":"ISO",
"calendarType":"iso8601"
}
}
我得到例外的是以下内容:
org.springframework.jms.support.converter.MessageConversionException: Failed to convert JSON message content; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDateTime
我能够通过以下注释暂时解决此问题:
@JsonSerialize(as = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class, as = LocalDateTime.class)
private LocalDateTime lastSeen;
但它们属于jackson datatype jsr310现在已不建议。
有什么办法/替代反序列化这个LocalDateTime属性,而不使用上述注解?或如何得到这个使用推荐jackson-modules-java8工作?
你写的解决办法是正确的做法。其他方法如下所述。公共类LocalDateTimeSerializer实现JsonSerializer {@覆盖公共JsonElement序列化(LocalDateTime localDateTime,类型类型,JsonSerializationContext jsonSerializationContext){即时瞬间= localDateTime.atZone(ZoneId.systemDefault())toInstant();日期日期= Date.from(即时);返回新JsonPrimitive(date.getTime()); }}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
Gson gson = gsonBuilder.create();
另一种方法。任何尝试。尽量日期时间格式更改为字符串。 “2011-04-08T09:00:00”。纳米等多种格式是如此复杂,我不能从你什么日期时间正是你所谈论的lastseen JSON告诉。它忽略了时区也因此当地的时间可以在任何地方部署的解决方案,如果你在3台不同的时区的机器的本地时间不正确部署。使用此字符串格式,或使自己“2011-04-08T09:00:00”
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
@JsonDeserialize(using = CustomJsonDateDeserializer.class)