【问题标题】:Custom Date deserializing: Jackson自定义日期反序列化:杰克逊
【发布时间】:2017-01-31 11:44:28
【问题描述】:

我正在尝试像这样为我的日期使用自定义格式:

public class CustomDateMappingDeserialize extends JsonDeserializer<Date>{

    @Override
    public Date deserialize(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext) throws IOException, JsonProcessingException {
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String date = paramJsonParser.getText();
            try {
                Date formattedDate= format.parse(date);
              return formattedDate;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

    }

}

日期为 2011-04-08 09:00:00 解析后我在 FormattedDate 中得到相同的日期,没有例外。

我有什么遗漏吗?

谢谢

【问题讨论】:

  • 为我打印formattedDate 显示Fri Apr 08 00:00:00 CEST 2011。正如预期的那样在午夜。问题是什么 ? (老实说,我很惊讶这在没有时间模式的情况下工作;))

标签: java jackson


【解决方案1】:

问题是对象日期总是会附加一个时间,所以如果你想把它删掉,你可以把它转换成这样的字符串:

String input = paramJsonParser.getText();
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // this has to be like your input
Date date = inputFormatter.parse(input);

DateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd");
String output = outputFormatter.format(date); // Output : yyyy-MM-dd

【讨论】:

  • The thing is that the Object Date will always append a Time 使用 SimpleDateFormat (没有时间),这不会恢复值,所以它将是00:00:00。所以日期会有所不同。但是如果这是要求的输出是正确的
  • 确实@AxelH,我个人不赞成丢失可能有用的信息,但我猜他想要它,所以我只是发布了它。我使用的解决方案是一个序列化程序来隐藏我不想在 gui 中看到的信息,但将所有信息保留在数据库中。对他来说也可能是一件有趣的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2019-08-04
  • 2021-08-12
  • 2014-01-31
  • 1970-01-01
  • 2013-08-11
  • 2017-01-30
相关资源
最近更新 更多