springobjectmapper

How print Date as Date using ObjectMapper in Spring App?


I am using Spring XML App (not Spring Boot and can't move), when I used below code I am getting details value for Date, what I want to just print yyyy-MM-dd format.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.text.SimpleDateFormat;
import java.time.LocalDate;

public class MainDemo {
    public static void main(String[] args) throws JsonProcessingException {
        Employee employee = Employee.builder().firstName("John").lastName("Doe").salary(10000L).joiningDate(LocalDate.now()).build();

        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(dateFormat);

        String json = mapper.writeValueAsString(employee);
        System.out.println(json);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
class Employee {
    private String firstName;
    private String lastName;
    private Long salary;
    private LocalDate joiningDate;
}

Output -

{"firstName":"John","lastName":"Doe","salary":10000,"joiningDate":{"year":2024,"month":"MAY","dayOfMonth":28,"monthValue":5,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"TUESDAY","dayOfYear":149,"era":"CE","leapYear":true}}

I simply wants to print date as 2024-May-25


Solution

  • I was able to solve the issue by adding below code

    Employee employee = Employee.builder().firstName("John").lastName("Doe").salary(10000L).joiningDate(LocalDate.now()).build();
    
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JavaTimeModule());
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    
            String json = mapper.writeValueAsString(employee);
            System.out.println(json);
    

    Result:

    {"firstName":"John","lastName":"Doe","salary":10000,"joiningDate":"2024-05-28"}