Я сталкиваюсь с следующей ошибкой при попытке вернуть пользовательский errorresponse объект с полем localdateTime с использованием Джексона в моем приложении Spring Boot:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.taskflow.taskflow.exceptions.ErrorResponse["timestamp"])
Проблема:
Несмотря на добавление необходимой конфигурации Джексона, я все еще получаю ошибку, указывающую на то, что localdatetime не поддерживается по умолчанию. Чтобы справиться с ответами на ошибку.
Что я попробовал:
Добавлен jackson-datatype-jsr310 . @JsonFormat в поле localDateTime в errorResponse .
Вопрос:
Как я могу правильно сериализовать localdateTeTem Ошибка?@Component
public class AuthenticationEntryPointJwt implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
ErrorResponse errorResponse = new ErrorResponse(
HttpServletResponse.SC_FORBIDDEN,
"Forbidden",
"You do not have permission to access this resource.",
request.getRequestURI()
);
< /code>
errorresponse.java:
@Getter
@Setter
public class ErrorResponse {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "UTC")
private LocalDateTime timestamp;
private int status;
private String error;
private String message;
private String path;
public ErrorResponse(int status, String error, String message, String path) {
this.timestamp = LocalDateTime.now();
this.status = status;
this.error = error;
this.message = message;
this.path = path;
}
}
< /code>
Я попытался добавить JacksonConfig, но все еще такая же проблема. < /p>
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper(){
return new ObjectMapper()
.registerModule(new JavaTimeModule()) // Enables LocalDateTime serialization
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // Ensures proper formatting
}
}
< /code>
pom.xml
com.fasterxml.jackson.core
jackson-databind
2.18.2
com.fasterxml.jackson.datatype
jackson-datatype-jsr310
2.18.2
com.fasterxml.jackson.core
jackson-annotations
2.18.2
Подробнее здесь: https://stackoverflow.com/questions/794 ... n-handling