Reputation: 1506
I have an issue with mapping a JSON to my DTO that has a LocalDateTime
.
I've followed this thread: JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value
Added to build.gradle
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.11.0'
Here is my variable in my DTO:
@Data
public class MyDto {
private Long teamId;
private Map<String, List<Long>> details;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime dateOccurred;
}
And added this
public class MyApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
}
Did I miss something? I'm getting this error
org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2020-06-16 11:12:46')
Thank you!
Upvotes: 0
Views: 10545
Reputation: 1506
Thank you to @mohammedkhan for the guide!
In this answer: JSON Java 8 LocalDateTime format in Spring Boot
There's already a setting in spring-boot there's no need to @Autowire
the ObjectMapper
dd this annotation for the Json Deserializer
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime dateOccurred;
Thank you!
Upvotes: 2