Gson日期转化报错

当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);
    }
}

发布了99 篇原创文章 · 获赞 46 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_35890572/article/details/103511195