feiyu02
2025-08-14 f373bbf83d9d2a7e5f96118d7dcd658c9fea8bc8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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<BgTaskStatus> {
 
    @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);
    }
}