【发布时间】:2017-06-18 03:49:06
【问题描述】:
我最近将我们的一些序列化从Jackson 切换到Gson。发现 Jackson 将日期序列化为 long。
但是,Gson 默认将日期序列化为字符串。
使用 Gson 时如何将日期序列化为长整数?谢谢。
【问题讨论】:
标签: java json date jackson gson
我最近将我们的一些序列化从Jackson 切换到Gson。发现 Jackson 将日期序列化为 long。
但是,Gson 默认将日期序列化为字符串。
使用 Gson 时如何将日期序列化为长整数?谢谢。
【问题讨论】:
标签: java json date jackson gson
第一种类型的适配器进行反序列化,第二种类型的适配器进行序列化。
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
.registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
.create();
用法:
String jsonString = gson.toJson(objectWithDate1);
ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
assert objectWithDate1.equals(objectWithDate2);
【讨论】:
你可以用一种类型的适配器做两个方向:
public class DateLongFormatTypeAdapter extends TypeAdapter<Date> {
@Override
public void write(JsonWriter out, Date value) throws IOException {
if(value != null) out.value(value.getTime());
else out.nullValue();
}
@Override
public Date read(JsonReader in) throws IOException {
return new Date(in.nextLong());
}
}
Gson 构建器:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateLongFormatTypeAdapter())
.create();
【讨论】:
nextLong() 有点含蓄:( 赞成。