杰克逊@JsonFormat将日期转换为不正确的时区

时间:2019-03-27 21:31:14

标签: java spring date jackson annotations

我有一个来自JSON负载的值:

"callStartTime" : "2019-03-27 13:00:00"

Entity.java

@JsonProperty("callStartTime")
@Column(name = "call_start_dt", nullable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private Date callStartTime;

当我在控制台上打印它时,它说:

Wed Mar 27 08:00:00 CDT 2019

我想和json负载中的一样。我该如何解决?

我只是从json获取日期,并将其写入datetime列中的mysql db。

4 个答案:

答案 0 :(得分:1)

尝试一下

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private Date callStartTime;

答案 1 :(得分:1)

java.util.Date不捕获时区数据。它只知道自那个时代以来的毫秒数。

您可以尝试使用jackson-modules-java8中的一个模块,然后反序列化为ZonedDateTime的实例,这是时区感知的。

编辑:尝试以此为基础使其工作:

testCombo.setButtonCell(new ListCell<>() {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {return;} // this is the solution: DO NOT ERASE ON empty=true!
        // further logic copied from the solution in the default skin: 
        // see ComboBoxListViewSkin.updateDisplayText
        // (default testing for "item instanceof Node" omitted for brevity)
        final StringConverter<String> c = testCombo.getConverter();
        final String promptText = testCombo.getPromptText();
        String s = item == null && promptText != null ? promptText
                : c == null ? (item == null ? null : item.toString()) : c.toString(item);
        setText(s);
        setGraphic(null);
    }
});

答案 2 :(得分:0)

简单的解决方案:我通过将数据类型更改为String来解决它,这完成了我捕获来自JSON负载的值的目标。使用Date和其他数据类型将值转换为不同的时区。

@JsonProperty("callStartTime")
@Column(name = "call_start_dt", nullable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private **String** callStartTime;

答案 3 :(得分:0)

有两种可能的解决方案:

1。定义ObjectMapper bean并设置日期格式。

@Bean
public ObjectMapper objectMapper()
{
   ObjectMapper objectMapper = new ObjectMapper();

   DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   objectMapper.setDateFormat(df);
       return objectMapper;
}

2。使用@JsonFormat

设置特定字段的日期格式
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private Date createTime;