杰克逊反序列化LocalDateTime

时间:2020-10-04 01:03:46

标签: spring-mvc jackson date-format jackson-databind

我有一个类似下面的时间字段值:

    public Object getExcelData(String sheetName, String colName, int rowNum) {

    int col_num = -1;
    int index = workbook.getSheetIndex(sheetName);
    if (index == -1)
        return "";

    sheet = workbook.getSheetAt(index);

    row = sheet.getRow(rowNum - 2);

    for (int i = 0; i < row.getLastCellNum(); i++) {
        if (row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
            col_num = i;
    }

    row = sheet.getRow(rowNum - 1);
    cell = row.getCell(col_num);

    DataFormatter formatter = new DataFormatter();
    Object excelData = formatter.formatCellValue(cell);

    return excelData;

}

我不知道如何将其表示为日期格式。

我需要将其反序列化为LocalDateTime字段。

我曾经这样尝试过

2020-10-01T15:30:27.4394205+03:00

但不起作用。我该如何反序列化? 顺便说一下,我正在使用弹簧靴。而该值将传递给其余的控制器请求主体。

3 个答案:

答案 0 :(得分:2)

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX")
private LocalDateTime timestamp;

答案 1 :(得分:1)

将模式替换为pattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME

您的日期时间字符串已经采用DateTimeFormatter.ISO_OFFSET_DATE_TIME指定的格式,这是OffsetDateTime#parse使用的默认格式。

演示:

import java.time.LocalDateTime;
import java.time.OffsetDateTime;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "2020-10-01T15:30:27.4394205+03:00";

        // Parse the date-time string into OffsetDateTime
        OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr);
        System.out.println(odt);

        // LocalDateTime from OffsetDateTime
        LocalDateTime ldt = odt.toLocalDateTime();
        System.out.println(ldt);
    }
}

输出:

2020-10-01T15:30:27.439420500+03:00
2020-10-01T15:30:27.439420500

答案 2 :(得分:0)

为其编写自定义反序列化器:

@Log4j2
public class CustomLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

 public CustomLocalDateTimeDeserializer() {
    this(null);
}
    private CustomLocalDateTimeDeserializer(Class<LocalDateTime> t) {
        super(t);
    }

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String date = jsonParser.getText();
        try {
            return LocalDateTime.parse(date);
        } catch (Exception ex) {
            log.debug("Error while parsing date: {} ", date, ex);
            throw new RuntimeException("Cannot Parse Date");
        }
    }
}

现在,使用反序列化器:

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
 @JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
 private LocalDateTime timestamp;

类似地,如果您需要对其进行序列化,也可以编写自定义序列化器。

相关问题