jackson parse pojo to json



我需要将java对象versementDTO转换为json字符串Historique,这个DTO包含一些日期,jackson正在将日期转换为这样的对象:"dateValidation";:{"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);
}
}
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));
}
}

相关内容

  • 没有找到相关文章

最新更新