package com.nbport.zgwl.contractlaunch.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        // 注册 Java8 时间模块，解决 LocalDateTime 序列化失败
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 配置 LocalDateTime 格式化输出：yyyy-MM-dd HH:mm:ss
        javaTimeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        OBJECT_MAPPER.registerModule(javaTimeModule);
        // 美化输出（可选，让日志更好看）
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter();
    }

    public static String toJson(Object obj) {
        if (obj == null) {
            return "null";
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            // 序列化失败时返回 toString，保证不报错
            return obj.toString();
        }
    }
}