如何在Spring应用程序中使用ObjectMapper将日期打印为日期?

问题描述 投票:0回答:1

我正在使用 Spring XML 应用程序(不是 Spring Boot 并且无法移动),当我使用下面的代码时,我得到了日期的详细信息值,我只想打印 yyyy-MM-dd 格式。

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;
}

输出-

{"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}}

我只是想将日期打印为 2024年5月25日

spring objectmapper
1个回答
0
投票

我能够通过添加以下代码来解决该问题

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);

结果:

{"firstName":"John","lastName":"Doe","salary":10000,"joiningDate":"2024-05-28"}
© www.soinside.com 2019 - 2024. All rights reserved.