gpt4 book ai didi

java - 使用 Gson 将 Java 8 LocalDate 序列化为 yyyy-mm-dd

转载 作者:行者123 更新时间:2023-12-02 01:28:47 28 4
gpt4 key购买 nike

我正在使用 Java 8 和最新的 RELEASE Gson 的版本(通过 Maven) 。如果我序列化 LocalDate 我得到这样的东西

"birthday": {
"year": 1997,
"month": 11,
"day": 25
}

我更喜欢的地方 "birthday": "1997-11-25" 。 Gson 是否还支持更简洁的开箱即用格式,或者我是否必须为 LocalDate 实现自定义序列化器?是?

(我尝试过 gsonBuilder.setDateFormat(DateFormat.SHORT) ,但这似乎没有什么区别。)

最佳答案

在进一步通知之前,我已经实现了一个自定义序列化器,如下所示:

class LocalDateAdapter implements JsonSerializer<LocalDate> {

public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-mm-dd"
}
}

它可以安装,例如像这样:

Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();

关于java - 使用 Gson 将 Java 8 LocalDate 序列化为 yyyy-mm-dd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564139/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com