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}java

百度沒搜到,google了一下 https://www.soinside.com/question/FvzpUvjQeuEXXnHFCCkJWm<br> 先實現一個類git

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

而後github

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/json

相關文章
相關標籤/搜索