setDateFormat(String pattern)方法
决定序列化和反序列化 java.util.Date,java.sql.Timestamp,java.sql.Timestamp的格式
并不支持localdata 所以需要手写一个 适配器来完成
private Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd") .registerTypeAdapter(LocalDate.class,new LocalDataTypeAdapter()) .create();
package com.chinagoods.personnel.config; import com.google.gson.*; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; /** * @Author: {---chenzhichao---} * @Date: 2020/6/2 20:04 */ public class LocalDataTypeAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> { private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); @Override public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (!(jsonElement instanceof JsonPrimitive)){ throw new JsonParseException("The date should be a string value"); } return null; } @Override public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String createTime = dateTimeFormatter.format(localDate); return new JsonPrimitive(createTime); } }