实现自定义的反序列化器并将注解@JsonDeserialize(using = DateDeserializer.class)
添加到您的字段中。
看一个例子:
您的Json-Bean:
public class Foo {
private String name;
@JsonProperty
@JsonDeserialize(using = DateDeserializer.class)
private Map<String, Object> dates;
[...]
}
反序列化器:
public class DateDeserializer extends JsonDeserializer<Map<String, Object>> {
private TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};
@Override
public Map<String, Object> deserialize(JsonParser p, DeserializationContext ctxt, Map<String, Object> target) throws IOException, JsonProcessingException {
Map<String, Long> map = new ObjectMapper().readValue(p, typeRef);
for(Entry<String, Long> e : map.entrySet()){
Long value = e.getValue();
String key = e.getKey();
if(value instanceof Long){
target.put(key, new Date(value));
} else {
target.put(key, value);
}
}
return target;
}
@Override
public Map<String, Object> deserialize(JsonParser paramJsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return this.deserialize(paramJsonParser, ctxt, new HashMap<>());
}
}
简单测试:
public static void main(String[] args) throws Exception {
Foo foo1 = new Foo();
foo1.setName("foo");
foo1.setData(new HashMap<String, Object>(){{
put("date", new Date());
put("bool", true);
put("string", "yeah");
}});
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(foo1);
System.out.println(jsonStr);
Foo foo2 = mapper.readValue(jsonStr, Foo.class);
System.out.println(foo2.equals(foo1));
}
Object
,Jackson 无法区分日期和实际的 long 类型。如果可能的话,您可以创建一个包装器来保存 Java 类型信息,并使用它来反序列化实际值,或者(如果不行)将日期格式化为 ISO-8601 字符串是否可行?这样,您就可以检查该值是否与预期模式匹配并转换为日期。 - dpr"[date]"
的东西,然后将其反序列化为日期。 - Steffen Harbich