杰克逊时间戳错误的反序列化

时间:2019-02-12 08:59:06

标签: java json jackson timestamp deserialization

我有一个自定义的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年以后停止对其进行解析。

2 个答案:

答案 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吗?