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

How can we format date using Jackson library in Java?

PHPz
Release: 2023-09-15 09:37:02
forward
983 people have browsed it

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)
Copy after login

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

Output

Employee [birthDate=Mon Dec 08 00:00:00 IST 1980]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template