Tag Archives: Jackson

Jackson localdatetime to string error: jsr310 [How to Solve]

error code

public static void main(String[] args)throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    final LocalDateTime localDateTime = LocalDateTime.now();
    final String s = objectMapper.writeValueAsString(localDateTime);
    System.out.println(s);
}

Error

reason

The date was not formatted during conversion

Solution:

public static void main(String[] args)throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    
        // Date and time formatting
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // Set the serialization format of LocalDateTime
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        objectMapper.registerModule(javaTimeModule);

    final LocalDateTime localDateTime = LocalDateTime.now();
    final String s = objectMapper.writeValueAsString(localDateTime);
    System.out.println(s);
}

Exception jsonmappingexception: out of start_ ARRAY token

1 problem
When a new HTTP interface is called and the data is parsed, an exception is raised:
Under Caused by: com. Fasterxml. Jackson. Databind. JsonMappingException: Can not deserialize the instance of the com. Out of XXX START_ARRAY token
The second analysis
If you look at the JSON data for the data, it’s an array. The original one is encapsulated as response.
So, you can encapsulate. Modify parsing without encapsulation:

objectMapper.readValue(json,XXOjject[].class);

This is an array object that can be converted to a list and returned normally.