package cn.flightfeather.supervision.common.executor; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * BgTaskStatus类的自定义序列化类 解决了计算属性无法序列化的问题 * by hc 2024.12.10 */ public class BgTaskStatusJsonSerializer implements JsonSerializer { @Override public JsonElement serialize(BgTaskStatus bgTaskStatus, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); // 序列化type jsonObject.addProperty("type", String.valueOf(bgTaskStatus.getType())); // 序列化id jsonObject.addProperty("id", bgTaskStatus.getId()); // 序列化name jsonObject.addProperty("name", bgTaskStatus.getName()); // 序列化status jsonObject.addProperty("status", String.valueOf(bgTaskStatus.getStatus())); // 序列化startTime jsonObject.addProperty("startTime", formatLocalDateTime(bgTaskStatus.getStartTime())); // 序列化endTime jsonObject.addProperty("endTime", formatLocalDateTime(bgTaskStatus.getEndTime())); // 序列化createTime jsonObject.addProperty("createTime", formatLocalDateTime(bgTaskStatus.getCreateTime())); // 序列化 计算属性runTime jsonObject.addProperty("runTime", bgTaskStatus.getRunTime()); // 序列化extra if (bgTaskStatus.getExtra() != null) { jsonObject.add("extra", context.serialize(bgTaskStatus.getExtra())); } return jsonObject; } private String formatLocalDateTime(LocalDateTime localDateTime) { // 如果LocalDateTime为null,则返回null if (localDateTime == null) { return null; } // 格式化LocalDateTime return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime); } }