我们如何使用Java中的Jackson库格式化日期?
一个杰克逊 是一个基于Java库,它可以是有用的Java对象到JSON和JSON转换为Java对象。JacksonAPI比其他API更快,需要较少的内存区域,并且适合大型对象。我们可以使用格式的日期setDateFormat()的ObjectMapper 类。在将时间值序列化为字符串并从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);
}
}
//员工阶层
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]
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志