繁体   English   中英

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

[英]Jackson Timestamp wrong deserialization

我有一个自定义对象映射器类:

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;
    }
}

}

我做错了什么? jackson 似乎认为时间戳字符串是一个整数,并且在 2019 年之后停止解析它。

这种方法有两个问题。

首先,有一个可疑的import语句:

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]);

可能是 Jackson 没有将Timestamp识别为日期类型,因此不依赖DateFormat

您可以尝试使用Java.util.Date而不是Timestamp吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM