Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để định dạng ngày bằng thư viện Gson trong Java?


A Gson là một thư viện JSON cho Java, được tạo bởi Google . Bằng cách sử dụng Gson, chúng ta có thể tạo JSON và chuyển đổi JSON thành các đối tượng java. Chúng tôi có thể tạo một phiên bản Gson bằng cách tạo một phiên bản GsonBuilder và gọi điện cho với create () phương pháp. GsonBuilder (). SetDateFormat () phương thức cấu hình Gson để tuần tự hóa các đối tượng Ngày theo mẫu được cung cấp.

Cú pháp

public GsonBuilder setDateFormat(java.lang.String pattern)

Ví dụ

import java.util.Date;
import com.google.gson.*;
public class DateformatTest {
   public static void main(String[] args) {
      Employee emp = new Employee(115, "Surya", new Date(), 25000.00);
      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
      String result = gson.toJson(emp);
      System.out.println(result);
   }
}
// Employee class
class Employee {
   private int id;
   private String name;
   private Date doj;
   private double salary;
   public Employee(int id, String name, Date doj, double salary) {
      this.id = id;
      this.name = name;
      this.doj = doj;
      this.salary = salary;
   }
}

Đầu ra

{"id":115,"name":"Surya","doj":"2019-09-26","salary":25000.0}