简体   繁体   中英

LocalDateTime parsing with jackson

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM