Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. The Jackson API is faster than other APIs, requires less memory area, and is good for large objects. We can use setDateFormat() of the ObjectMapper class to format the date. This method can be used to configure the default DateFormat when serializing time values to strings and deserializing from JSON strings.
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]
The above is the detailed content of How can we format date using Jackson library in Java?. For more information, please follow other related articles on the PHP Chinese website!