学习记录
以下是关于 Jackson 库中用于处理 JSON 序列化和反序列化的配置信息。
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss # 指定日期格式
time-zone: GMT+8 # 指定时区,东八区时间
serialization:
write-dates-as-timestamps: false # 写日期为时间戳(默认为true):否
测试上述配置的测试用例:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.jupiter.api.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JacksonConfigTest {
@Test
public void testJacksonConfig() throws Exception {
// 创建 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// 设置日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(dateFormat);
// 设置时区
TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
objectMapper.setTimeZone(timeZone);
// 序列化配置
objectMapper.enable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
// 创建示例对象
Date date = dateFormat.parse("2023-06-29 14:30:00");
ExampleObject exampleObject = new ExampleObject(date);
// 将示例对象转为 JSON 字符串
String json = objectMapper.writeValueAsString(exampleObject);
// 预期的 JSON 字符串
String expectedJson = "{\"date\":\"2023-06-29 14:30:00\"}";
// 断言 JSON 字符串是否相等
assertEquals(expectedJson, json);
}
// 示例对象类
public static class ExampleObject {
private Date date;
public ExampleObject(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
}