如何使用 Java 中的 Jackson 库格式化日期?

javajsonobject oriented programmingprogramming更新于 2025/7/14 8:12:17

Jackson  是一个基于 Java 的库,它可用于将 Java 对象转换为 JSON 以及将 JSON 转换为 Java 对象。Jackson API 比其他 API 更快,需要的内存区域更少,并且适用于大型对象。我们可以使用 ObjectMapper  类的 setDateFormat() 格式化日期。在将时间值序列化为字符串并从 JSON 字符串反序列化时,此方法可用于配置默认 DateFormat 。

语法

public ObjectMapper setDateFormat(DateFormat dateFormat)

示例

import java.io.*;
import java.text.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;

public class JacksonDateformatTest {
   final static ObjectMapper mapper = new ObjectMapper();
   public static void main(String[] args) throws Exception {
      JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
      mapper.setDateFormat(df);
      jacksonDateformat.dateformat();
}
   public void dateformat() throws Exception {
      String json = "{\"birthDate\":\"1980-12-08\"}";
      Reader reader = new StringReader(json);
      Employee emp = mapper.readValue(reader, Employee.class);
      System.out.println(emp);
   }
}

// Employee class
class Employee implements Serializable {
   private Date birthDate;
   public Date getBirthDate() {
      return birthDate;
   }
   public void setBirthDate(Date birthDate) {
      this.birthDate = birthDate;
   }
   @Override
   public String toString() {
      return "Employee [birthDate=" + birthDate + "]";
   }
}

输出

Employee [birthDate=Mon Dec 08 00:00:00 IST 1980]

相关文章


有用资源