当Long型的Json数据,反序列化成Date属性的对象的时候,会报转化错误。在初始化Gson时,可以注册一个日期专用解析器,就解决问题了
public class JsonUtil {
private JsonUtil() {
}
private static Gson gson;
private static Gson getGson() {
if (gson == null) {
synchronized (JsonUtil.class) {
if (gson == null) {
GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss");
JsonDeserializer deserializer = (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong());
builder.registerTypeAdapter(Date.class, deserializer);
gson = builder.create();
}
}
}
return gson;
}
public static <T> String toJson(T object) {
return getGson().toJson(object);
}
public static <T> T fromJson(String json, Type type) {
return getGson().fromJson(json, type);
}
public static <T> T fromJson(String json, Class<T> clazz) {
return getGson().fromJson(json, clazz);
}
}