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

相关文章
相关标签/搜索