我使用的是Java 8和Gson的最新RELEASE
版本(通过Maven)。
如果我序列化LocalDate
我得到类似的东西
"birthday": {
"year": 1997,
"month": 11,
"day": 25
}
我更喜欢"birthday": "1997-11-25"
。 Gson是否也支持更简洁的开箱即用格式,或者我是否必须为LocalDate
实现自定义序列化器?
(我已尝试gsonBuilder.setDateFormat(DateFormat.SHORT)
,但这似乎没有什么区别。)
答案 0 :(得分:35)
直到另行通知,我已经实现了一个自定义序列化器,如下所示:
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();
答案 1 :(得分:8)
我使用以下内容,支持读/写和空值:
Docker Toolbox
注册为@Drux的人说:
class LocalDateAdapter extends TypeAdapter<LocalDate> {
@Override
public void write(final JsonWriter jsonWriter, final LocalDate localDate) throws IOException {
if (localDate == null) {
jsonWriter.nullValue();
} else {
jsonWriter.value(localDate.toString());
}
}
@Override
public LocalDate read(final JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
return null;
} else {
return LocalDate.parse(jsonReader.nextString());
}
}
}
编辑2019-04-04 一个更简单的实现
return new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
您可以通过注册private static final class LocalDateAdapter extends TypeAdapter<LocalDate> {
@Override
public void write( final JsonWriter jsonWriter, final LocalDate localDate ) throws IOException {
jsonWriter.value(localDate.toString());
}
@Override
public LocalDate read( final JsonReader jsonReader ) throws IOException {
return LocalDate.parse(jsonReader.nextString());
}
}
包装的版本来添加null
支持:
nullSafe()
答案 2 :(得分:0)
支持序列化和反序列化的Kotlin版本:
class LocalDateTypeAdapter : TypeAdapter<LocalDate>() {
override fun write(out: JsonWriter, value: LocalDate) {
out.value(DateTimeFormatter.ISO_LOCAL_DATE.format(value))
}
override fun read(input: JsonReader): LocalDate = LocalDate.parse(input.nextString())
}
注册您的GsonBuilder。使用nullSafe()
来获得null
支持:
GsonBuilder().registerTypeAdapter(LocalDate::class.java, LocalDateTypeAdapter().nullSafe())