我有一个自定义的objectmapper-class:
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;
}
}
}
我错了什么?似乎杰克逊认为timestamp-string是一个整数,ans会在2019年以后停止对其进行解析。
答案 0 :(得分:2)
此方法有两个问题。
首先,有一个可疑的导入语句:
import org.codehaus.jackson.map.ObjectMapper;
org.codehaus
是当前com.fasterxml
的前身。尚不清楚是否有意使用它,但是ObjectMapper
的导入应该是
import com.fasterxml.jackson.databind.ObjectMapper;
第二,不能直接从像这样的普通字符串中读取时间戳
String timestamp = "2019-02-12T07:53:11+0000";
ObjectMapper
需要JSON字符串。所以如果是
{ "timestamp": "2019-02-12T07:53:11+0000" }
和包装类
class TimestampWrapper {
private Timestamp timestamp;
// getter + setter for timestamp
}
然后测试序列将正确执行:
String timestamp = "{ \"timestamp\": \"2019-02-12T07:53:11+0000\" }";
CustomObjectMapper customObjectMapper = new CustomObjectMapper();
TimestampWrapper result = customObjectMapper.readValue(timestamp, TimestampWrapper.class);
System.out.println(result.getTimestamp());
更新:
或者,不使用专用包装器类,就可以从JSON数组反序列化它:
String timestamp = "[ \"2019-02-12T07:53:11+0000\" ]";
CustomObjectMapper customObjectMapper = new CustomObjectMapper();
Timestamp[] result = customObjectMapper.readValue(timestamp, Timestamp[].class);
System.out.println(result[0]);
答案 1 :(得分:0)
可能是因为杰克逊没有将Timestamp
识别为日期类型,所以也没有依赖DateFormat
您可以尝试使用Java.util.Date
而不是Timestamp
吗?