我正在使用Java 8和Gson的最新RELEASE版本(通过Maven).如果我序列化我得到这样的东西LocalDate
"birthday": {
"year": 1997,
"month": 11,
"day": 25
}
Run Code Online (Sandbox Code Playgroud)
在哪里我会更喜欢"birthday": "1997-11-25".Gson是否也支持更简洁的开箱即用格式,或者我是否必须为LocalDates 实现自定义序列化器?
(我试过了gsonBuilder.setDateFormat(DateFormat.SHORT),但这似乎没有什么区别.)
Dru*_*rux 43
直到另行通知,我已经实现了这样的自定义序列化器:
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"
}
}
Run Code Online (Sandbox Code Playgroud)
它可以安装,例如:
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
Run Code Online (Sandbox Code Playgroud)
Sam*_*num 10
我使用以下内容,支持读/写和空值:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
注册为@Drux时说:
return new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
Run Code Online (Sandbox Code Playgroud)
编辑2019-04-04一个更简单的实现
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());
}
}
Run Code Online (Sandbox Code Playgroud)
您可以null通过注册nullSafe()包装版本来添加支持:
new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe())
Run Code Online (Sandbox Code Playgroud)
支持序列化和反序列化的 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())
}
Run Code Online (Sandbox Code Playgroud)
注册您的 GsonBuilder。包装nullSafe()用于null支持:
GsonBuilder().registerTypeAdapter(LocalDate::class.java, LocalDateTypeAdapter().nullSafe())
Run Code Online (Sandbox Code Playgroud)