使用Gson将Java 8 LocalDate序列化为yyyy-mm-dd [英] Serialize Java 8 LocalDate as yyyy-mm-dd with Gson
问题描述
我正在使用Java 8和 Gson 的最新RELEASE
版本(通过Maven).
如果我将 LocalDate
序列化,则会得到像这样的东西
I am using Java 8 and the latest RELEASE
version (via Maven) of Gson.
If I serialize a LocalDate
I get something like this
"birthday": {
"year": 1997,
"month": 11,
"day": 25
}
我更喜欢"birthday": "1997-11-25"
的地方. Gson是否还支持开箱即用的更简洁格式,还是我必须为LocalDate
实现自定义序列化程序?
where I would have preferred "birthday": "1997-11-25"
. Does Gson also support the more concise format out-of-the-box, or do I have to implement a custom serializer for LocalDate
s?
(我尝试过gsonBuilder.setDateFormat(DateFormat.SHORT)
,但这似乎没有什么不同.)
(I've tried gsonBuilder.setDateFormat(DateFormat.SHORT)
, but that does not seem to make a difference.)
推荐答案
在没有另行通知之前,我已经实现了一个自定义序列化器,如下所示:
Until further notice, I have implemented a custom serializer like so:
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"
}
}
它可以安装例如像这样:
It can be installed e.g. like so:
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
这篇关于使用Gson将Java 8 LocalDate序列化为yyyy-mm-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!