考虑以下示例:
我有一个json string = {"timestamp":1504111920}
需要转换为CodeTimestamp类。上面的json字符串中的时间戳位于epoch秒中。
CodeTimestamp类:
@Getter
@Setter
@NoArgsConstructor
class CodeTimestamp {
private Date timestamp;
}
通过直接使用fastxml jackson mapper,我将无法获得正确的日期,因为它假定时间戳为epoch毫秒。所以,我需要编写一个自定义反序列化器。
但是,我无法编辑/修改CodeTimestamp类。有没有办法在mixin中编写JsonDeserializer?
我在反序列化时遇到问题。以下是代码:
public abstract class StreamRecordMixIn {
@JsonDeserialize(using = UnixTimestampDeserializer.class)
private Date approximateCreationDateTime;
}
public class UnixTimestampDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
String unixTimestamp = parser.getText().trim();
return new Date(TimeUnit.SECONDS.toMillis(Long.valueOf(unixTimestamp)));
}
}
初始化和使用对象映射器的代码:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.addMixIn(CodeTimestamp.class, StreamRecordMixIn.class);
CodeTimestamp codeTimeStamp = objectMapper.readValue(payload, CodeTimestamp.class);
错误:
引起:java.lang.IllegalArgumentException:类com.test.TestConverter $ UnixTimestampDeserializer没有默认(无arg)构造函数 在com.fasterxml.jackson.databind.util.ClassUtil.createInstance(ClassUtil.java:378) 在com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.deserializerInstance(DefaultDeserializationContext.java:218) at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findDeserializerFromAnnotation(BasicDeserializerFactory.java:1735) 在com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.constructSettableProperty(BeanDeserializerFactory.java:730) 在com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.addBeanProps(BeanDeserializerFactory.java:507) 在com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:229) 在com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:142) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:403) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:352) 在com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264) ......还有23个
答案 0 :(得分:0)
这里的错误是自定义反序列化器未声明为静态。因此,如果我按照下面提到的那样使用它,那就可以了。
public static class UnixTimestampDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
String unixTimestamp = parser.getText().trim();
return new Date(TimeUnit.SECONDS.toMillis(Long.valueOf(unixTimestamp)));
}
}