我有字段 initiationDate
,它由 ToStringSerializer
类序列化为 ISO-8601 格式。
@JsonSerialize(using = ToStringSerializer.class)
private LocalDateTime initiationDate;
当我收到以下 JSON 时,
...
"initiationDate": "2016-05-11T17:32:20.897",
...
我想通过 LocalDateTime.parse(CharSequence text)
工厂方法反序列化它。我所有的尝试都以 com.fasterxml.jackson.databind.JsonMappingException
结束:
Can not instantiate value of type [simple type, class
java.time.LocalDateTime
] fromString
value ('2016-05-11T17:32:20.897'
); no single-String
constructor/factory method
我该如何实现?如何指定工厂方法?
编辑:
问题已通过包含 jackson-datatype-jsr310 module 得到解决到项目并使用 @JsonDeserialize
和 LocalDateTimeDeserializer
。
@JsonSerialize(using = ToStringSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime initiationDate;
最佳答案
Vanilla Jackson 没有办法从任何 JSON 字符串值反序列化 LocalDateTime
对象。
您有几个选择。您可以创建并注册自己的 JsonDeserializer
,它将使用 LocalDateTime#parse
。
class ParseDeserializer extends StdDeserializer<LocalDateTime> {
public ParseDeserializer() {
super(LocalDateTime.class);
}
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDateTime.parse(p.getValueAsString()); // or overloaded with an appropriate format
}
}
...
@JsonSerialize(using = ToStringSerializer.class)
@JsonDeserialize(using = ParseDeserializer.class)
private LocalDateTime initiationDate;
或者您可以添加 Jackson's java.time
extension到您的类路径并使用您的 ObjectMapper
注册适当的 Module
。
objectMapper.registerModule(new JavaTimeModule());
让 Jackson 为您进行转换。在内部,这使用具有标准格式之一的 LocalDateTime#parse
。幸运的是,它支持这样的值
2016-05-11T17:32:20.897
开箱即用。
关于java - LocalDateTime - 使用 LocalDateTime.parse 进行反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37166217/