如何在Java中使用Jackson库来格式化日期?
Jackson 是一个基于Java的库,可以用来将Java对象转换为JSON,以及将JSON转换为Java对象。与其他API相比,Jackson API更快,需要的内存空间更少,并且适用于大对象。我们可以通过ObjectMapper 类的setDateFormat()来格式化日期。这个方法可以用来配置默认的DateFormat ,在将时间值序列化为字符串和从JSON字符串反序列化时使用。
语法
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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP