如何使用 Java 中的 Gson 库格式化日期?
javajsonobject oriented programmingprogramming更新于 2025/7/13 15:40:17
Gson 是一个 Java 的 JSON 库,由 Google 创建。通过使用 Gson,我们可以生成 JSON 并将 JSON 转换为 Java 对象。我们可以通过创建 GsonBuilder 实例并调用 create() 方法创建一个 Gson 实例。GsonBuilder().setDateFormat() 方法将 Gson 配置为根据提供的模式序列化 Date 对象。
语法
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}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

