項目中使用 Jackson2ObjectMapperBuilder 配置了 LocalDate、LocalDateTime、ZonedDateTime 的 JSON 序列化/反序列化,需編寫 JUnit 測試驗證功能。
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true)
.serializerByType(LocalDate.class, new JsonSerializer<LocalDate>() {
@Override
public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(value.toString());
}
})
.deserializerByType(LocalDate.class, new JsonDeserializer<LocalDate>() {
@Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return LocalDate.parse(jp.getValueAsString());
}
})
// LocalDateTime、ZonedDateTime 同理...
;
return builder;
}
indentOutput(true) 美化輸出@SpringBootTest
@AutoConfigureMockMvc
class DateSerializationTest {
@Autowired
private ObjectMapper objectMapper;
@Test
void testLocalDateSerialization() throws Exception {
LocalDate date = LocalDate.of(2023, 10, 15);
String json = objectMapper.writeValueAsString(date);
assertEquals("\"2023-10-15\"", json);
LocalDate parsed = objectMapper.readValue(json, LocalDate.class);
assertEquals(date, parsed);
}
@Test
void testLocalDateTimeSerialization() throws Exception {
LocalDateTime dt = LocalDateTime.of(2023, 10, 15, 14, 30, 45);
String json = objectMapper.writeValueAsString(dt);
assertEquals("\"2023-10-15T14:30:45\"", json);
}
@Test
void testZonedDateTimeSerialization() throws Exception {
ZonedDateTime zdt = ZonedDateTime.of(2023, 10, 15, 14, 30, 45, 0, ZoneId.of("Asia/Shanghai"));
String json = objectMapper.writeValueAsString(zdt);
// 包含時區偏移,如 "2023-10-15T14:30:45+08:00"
assertTrue(json.contains("+08:00"));
}
@Test
void testDtoWithDates() throws Exception {
// 測試包含日期字段的 DTO 對象
EventDto dto = new EventDto("發布會", LocalDate.now(), LocalDateTime.now());
String json = objectMapper.writeValueAsString(dto);
System.out.println(json); // 觀察完整結構
assertNotNull(json);
}
}
// 測試用 DTO
class EventDto {
public String name;
public LocalDate date;
public LocalDateTime dateTime;
public EventDto(String name, LocalDate date, LocalDateTime dateTime) {
this.name = name; this.date = date; this.dateTime = dateTime;
}
}
@Autowired ObjectMapper 獲取 Spring 配置好的實例@JsonFormat 註解衝突jackson.time-zonejackson-datatype-jsr310 模塊(Spring Boot 默認已包含)