Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

729
Views
No se puede deserializar el valor del tipo java.time.LocalDateTime de String

Tengo la siguiente configuración:

 @Bean @Primary public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false); return objectMapper; }

y las siguientes dependencias:

 ext { springBootVersion = '1.5.2.RELEASE' } .... dependencies { compile('org.springframework.boot:spring-boot-starter-websocket') compile("org.springframework:spring-messaging") compile('org.springframework.boot:spring-boot-starter-actuator') compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile('org.springframework.boot:spring-boot-starter-validation') compile('org.springframework.boot:spring-boot-starter-web') compile group: 'net.jcip', name: 'jcip-annotations', version: '1.0' compile ("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") testCompile('org.springframework.boot:spring-boot-starter-test') }

Agregué el siguiente controlador:

 @PostMapping("/validation_test") public String testValidation(@Valid @RequestBody ClientInputMessage clientInputMessage, BindingResult result) { logger.info(Arrays.toString(result.getAllErrors().toArray())); return "main"; } public class ClientInputMessage { @NotEmpty private String num1; @NotEmpty private String num2; @Past private LocalDateTime date;

Si paso json así:

 { "num1":"324", "num2":123, "date":"2014-01-01" }

la aplicación imprime la siguiente salida:

 Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDateTime from String "2014-01-01": Text '2014-01-01' could not be parsed at index 10 at [Source: java.io.PushbackInputStream@1204f40f; line: 4, column: 8] (through reference chain: model.ClientInputMessage["date"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDateTime from String "2014-01-01": Text '2014-01-01' could not be parsed at index 10 at [Source: java.io.PushbackInputStream@1204f40f; line: 4, column: 8] (through reference chain: model.ClientInputMessage["date"])
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Respuesta original:

LocalDateTime en java no acepta "2014-01-01" como una cadena de fecha válida.

Alguna información adicional:

Si en realidad no le importa de qué tipo es su fecha (LocalDate, OffsetDate, ZonedDate, ...), puede convertirla en TemporalAccessor y luego usar DateTimeFormatter::parseBest para analizar la fecha.

PD
la cadena "2014-01-01T00:00:00" será válida para LocalDateTime

about 4 years ago · Santiago Trujillo Report

0

Simplemente puede decirle al deserializador que lo que viene debe ser una LocalDate incluso si tiene una LocalDateTime en la salida, teniendo cuidado de tener un setter alternativo para su variante de LocalDate .

algo como:

 @JsonDeserialize(as = LocalDate.class) @Past private LocalDateTime date; public void setDate(LocalDateTime input) { date = input; } public void setDate(LocalDate input) { date = input.atStartOfDay(); }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!