diff --git a/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/json/JsonUtils.java b/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/json/JsonUtils.java index 8bb876591..1432a242a 100644 --- a/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/json/JsonUtils.java +++ b/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/json/JsonUtils.java @@ -9,7 +9,10 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.cfg.MapperConfig; +import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import lombok.Getter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; @@ -25,27 +28,47 @@ import java.util.List; */ @Slf4j public class JsonUtils { - + // 静态的 ObjectMapper 实例,默认初始化 private static ObjectMapper objectMapper = new ObjectMapper(); + // 静态初始化块,确保默认配置和模块注册 static { - objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略 null 值 - objectMapper.registerModules(new JavaTimeModule()); // 解决 LocalDateTime 的序列化 + configureDefaultSettings(objectMapper); + // 解决 LocalDateTime 的序列化 + objectMapper.registerModule(new JavaTimeModule()); } /** - * 初始化 objectMapper 属性 + * 初始化 ObjectMapper,合并传入的配置并应用默认设置,但不注册模块 *

- * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean + * 通过此方法可以使用 Spring 创建的 ObjectMapper Bean,同时保留默认配置。 * - * @param objectMapper ObjectMapper 对象 + * @param inputObjectMapper Spring 提供的 ObjectMapper 对象,可以为 null */ - public static void init(ObjectMapper objectMapper) { - JsonUtils.objectMapper = objectMapper; + public static void init(ObjectMapper inputObjectMapper) { + // 如果传入的为 null,则保留现有实例并重新应用默认配置 + if (inputObjectMapper == null) { + configureDefaultSettings(objectMapper); + return; + } + + // 使用传入的 ObjectMapper 副本,避免外部修改影响 + objectMapper = inputObjectMapper.copy(); + // 应用默认设置,确保一致性,但不注册模块 + configureDefaultSettings(objectMapper); } + /** + * 配置默认设置,避免重复代码 + * @param mapper 要配置的 ObjectMapper 实例 + */ + private static void configureDefaultSettings(ObjectMapper mapper) { + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略 null 值 + } + + @SneakyThrows public static String toJsonString(Object object) { return objectMapper.writeValueAsString(object);