我们如何使用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]