Pre Merge pull request !170 from jackie/master-jdk17

pull/170/MERGE
jackie 2025-05-04 08:01:12 +00:00 committed by Gitee
commit 6b134ce5e4
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
1 changed files with 33 additions and 10 deletions

View File

@ -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
* <p>
* 使 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);