首页 > 文章列表 > 我们如何使用Java中的Jackson库来格式化日期?

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

java jackson 日期格式化
181 2023-09-06

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]