如何使用Java中的Gson库格式化日期?
一个GSON 是一个JSON库为Java,这是创建谷歌。通过使用Gson,我们可以生成JSON并将JSON转换为Java对象。我们可以通过创建GsonBuilder实例 并 使用 create()方法进行调用来创建Gson实例。GsonBuilder()。setDateFormat()方法根据所提供的图案配置GSON序列化对象的日期。
语法
public GsonBuilder setDateFormat(java.lang.String pattern)
示例
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 classclass 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;
}
}输出结果
{"id":115,"name":"Surya","doj":"2019-09-26","salary":25000.0}