【发布时间】:2019-07-05 20:54:18
【问题描述】:
我有一个自定义对象映射器类:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.codehaus.jackson.map.ObjectMapper;
public class CustomObjectMapper extends ObjectMapper {
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
public CustomObjectMapper() {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
this.setDateFormat(df);
}
还有一个单元测试:
@Test
public void testSerialization() throws JsonParseException, JsonMappingException, IOException {
String timestamp = "2019-02-12T07:53:11+0000";
CustomObjectMapper customObjectMapper = new CustomObjectMapper();
Timestamp result = customObjectMapper.readValue(timestamp, Timestamp.class);
System.out.println(result.getTime());
}
junit-test 给了我“2019”。
我尝试使用 customTimestampDeserializer:
public class CustomJsonTimestampDeserializer extends
JsonDeserializer<Timestamp> {
@Override
public Timestamp deserialize(JsonParser jsonparser,
DeserializationContext deserializationcontext) throws IOException,
JsonProcessingException {
String date = jsonparser.getText(); //date is "2019"
JsonToken token = jsonparser.getCurrentToken(); // is JsonToken.VALUE_NUMBER_INT
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
CustomObjectMapper.DATE_FORMAT);
try {
return new Timestamp(simpleDateFormat.parse(date).getTime());
} catch (ParseException e) {
return null;
}
}
}
我做错了什么?似乎杰克逊认为时间戳字符串是一个整数,并且在 2019 年之后停止解析它。
【问题讨论】:
-
你使用来自
java.sql的Timestamp吗? -
我建议你不要使用
SimpleDateFormat和Timestamp。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的Instant。
标签: java json jackson timestamp deserialization