Ali*_*aka 20
第一种类型的适配器执行反序列化,第二种类型适配器执行序列化.
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();
Run Code Online (Sandbox Code Playgroud)
用法:
String jsonString = gson.toJson(objectWithDate1);
ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
assert objectWithDate1.equals(objectWithDate2);
Run Code Online (Sandbox Code Playgroud)
Dan*_*ári 10
你可以用一种类型的适配器做两个方向:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
Gson建设者:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateLongFormatTypeAdapter())
.create();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7975 次 |
| 最近记录: |