Gson格式化LocalDateTime

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(resultData);

在使用Gson格式化LocalDateTime時,結果並沒有按照想象中的格式出現,而是出現了下面這種格式
“date”:{“year”:2019,“month”:11,“day”:17},“time”:{“hour”:22,“minute”:0,“second”:0,“nano”:0}

百度沒搜到,google了一下 https://www.soinside.com/question/FvzpUvjQeuEXXnHFCCkJWm

先實現一個類

public class LocalDateAdapter implements JsonSerializer<LocalDateTime> {
    @Override
    public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
}

然後

        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(LocalDateTime.class,new LocalDateAdapter()).create();
        return gson.toJson(resultData);

就可以了
“2019-11-17 22:00:00”
更多文章見個人博客 https://zheyday.github.io/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章