
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we format a date using the Jackson library in Java?
Jackson is a Java-based library, and it can be useful to convert Java objects to JSON and JSON to Java objects. A Jackson API is faster than other API, needs less memory, and is good for large objects.
We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.
Syntax of setDateFormat()
public ObjectMapper setDateFormat(DateFormat df)
Here, df is the DateFormat instance to be used for formatting dates.
Steps to format a date using Jackson in Java
Following are the steps to format a date using Jackson in Java:
- Add the Jackson library to your project.
- To add, you can use Maven or download the jar files from the Jackson website. Or add the following dependency to your pom.xml file if you are using Maven:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency>
- Import the necessary Jackson classes.
- Create an instance of the ObjectMapper.
- Use the setDateFormat() method of the ObjectMapper class to set the date format.
- Use the writeValueAsString() method to convert the Java object to JSON.
Example
In the example below, we will create a class Person with fields for name and date of birth. We will then format the date using Jackson's setDateFormat() method.
Following is the code to format a date using Jackson in Java:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.text.DateFormat; import java.text.SimpleDateFormat; public class DateFormatEx { public static void main(String[] args) throws JsonProcessingException { // Create an instance of the Person class Person person = new Person("Ansh", "2002-01-01"); // Create an instance of ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // Set the date format DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); objectMapper.setDateFormat(df); // Convert the Person object to JSON String json = objectMapper.writeValueAsString(person); System.out.println(json); } } class Person { private String name; private String dob; public Person() { } public Person(String name, String dob) { this.name = name; this.dob = dob; } public String getName() { return name; } public String getDob() { return dob; } }
Output
{"name":"Ansh","dob":"2002-01-01"}