Home >Java >javaTutorial >How can we format date using Jackson library in Java?

How can we format date using Jackson library in Java?

PHPz
PHPzforward
2023-09-15 09:37:021001browse

How can we format date using Jackson library in Java?

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.

Syntax

public ObjectMapper setDateFormat(DateFormat dateFormat)

Example

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 + "]";
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete