Jackson将pojo解析为json

zaqlnxep  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(192)

我需要将一个java对象versementDTO转换为json字符串Historique,这个DTO包含一些日期,Jackson将日期转换为这样的对象:“日期确认”:{"nano":0,"year":2007,"monthValue":2,"dayOfMonth":7,"hour":15,"minute":21,"second":24,"month":"FEBRUARY","dayOfWeek":"WEDNESDAY","dayOfYear":38,"chronology":{"id":"ISO","calendarType":"iso8601"}},我需要得到一个如下的值:“2007/02/21 15:21:24”,我得到以下错误:已解决

[org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2007-02-07T15:21:24": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2007-02-07T15:21:24' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2007-02-07T15:21:24": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2007-02-07T15:21:24' could not be parsed at index 10
 at [Source: (PushbackInputStream); line: 1, column: 95] (through reference chain: aws.lbackend.dto.VersementDTO["dateValidation"])]

感谢你的帮助!

public static String historizeInJson(VersementDTO pojo) {

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));

    objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
    try {
        String jsVDTO = objectMapper.writeValueAsString(pojo);
        //System.out.print("json dz : "+ jsVDTO);
        return jsVDTO;
    } catch (JsonProcessingException e) {
            LOGGER.info("failed conversion: Pfra object to Json", e);
        return null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
myzjeezk

myzjeezk1#

ObjectMapper objectMapper = new ObjectMapper();

SimpleModule module = new SimpleModule("ModuleDate2Json",
                new Version(1, 0, 0, null));
module.addSerializer(LocalDateTime.class, new LocalDateSerializer<LocalDateTime>());
        objectMapper.registerModule(module);

对于LocalDateSerialzer类:

public class LocalDateSerializer<L> extends JsonSerializer<LocalDateTime {

    public LocalDateSerializer() {
        super();
    }

    @Override
    public void serialize(LocalDateTime localDateTime, org.codehaus.jackson.JsonGenerator jsonGenerator, org.codehaus.jackson.map.SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    }
}

相关问题