You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot 2.7.18返回JSON含类路径,如何去除该冗余信息?

问题

使用SpringBoot 2.7.18开发时,自定义配置ObjectMapper后,/redis/set接口返回的JSON包含CommonResult类的完整类路径,格式为数组:

[   
    "com.lybb.ms.result.CommonResult",   
    {     
      "code": 200,     
      "status": 200,    
      "message": "success",     
      "data": true   
    } 
]

期望返回标准对象结构的JSON:

{     
    "code": 200,     
    "status": 200,     
    "message": "success",
    "data": true  
}

如何修改配置去除冗余的类路径信息?

相关配置与代码如下:

1. ObjectMapper配置类JackJsonConfig

@Configuration
public class JackJsonConfig {
    @Value("${spring.jackson.local-date-time-format}")
    String localDateTimeFormat;
    
    @Value("${spring.jackson.local-date-format}")
    String localDateFormat;
    
    @Value("${spring.jackson.local-time-format}")
    String localTimeFormat;
    
    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();;
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
    
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(
            LocalDateTime.class,
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimeFormat))
        );

        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(
            DateTimeFormatter.ofPattern(localDateFormat)
        ));

        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(
            DateTimeFormatter.ofPattern(localTimeFormat)
        ));

        javaTimeModule.addDeserializer(
            LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(localDateTimeFormat))
        );
    
        javaTimeModule.addDeserializer(
            LocalDate.class,
            new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDateFormat))
        );
        javaTimeModule.addDeserializer(
            LocalTime.class,
            new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimeFormat))
        );

        SimpleModule simpleModule = new SimpleModule()

        .addSerializer(Long.class, ToStringSerializer.instance)
        .addSerializer(BigDecimal.class, ToStringSerializer.instance);
    
        List<Module> moduleList = new ArrayList<>();
        moduleList.add(javaTimeModule);
        moduleList.add(simpleModule);
    
        objectMapper.registerModules(moduleList);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
        return objectMapper;
    }
}

2. application.yaml配置

spring:   
 jackson:     
  local-date-time-format: yyyy/MM/dd HH:mm:ss     
  local-date-format: yyyy/MM/dd     
  local-time-format: HH:mm:ss

3. Controller代码

@RequestMapping("/redis/set")     
@ResponseBody     
CommonResult<Boolean> redisSet(){         
  User user = userService.getById(1);         
  redisUtil.set("user1", user);         
  return CommonResult.success(Boolean.TRUE);    
}

4. CommonResult类定义

@Data 
public class CommonResult<T> implements Serializable {     
    private static final long serialVersionUID = -2102040891517300266L;     
    private long code;     
    private int status;     
    private String message;     
    private T data;
}
解决方案

问题根源在于ObjectMapper配置中的activateDefaultTyping方法,该方法会启用Jackson全局默认类型信息序列化,将对象序列化为包含类路径的数组格式。只需移除该行配置即可解决问题。

修改后的JackJsonConfig中objectMapper方法关键部分:

// 移除这一行全局类型序列化配置
// objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

// 保留其他原有配置
objectMapper.registerModules(moduleList);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

如果确实需要为特定类添加类型信息(比如反序列化时区分子类),可以在目标类上使用@JsonTypeInfo注解,而非全局启用默认类型序列化。示例如下:

@Data 
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public class CommonResult<T> implements Serializable {     
    // 类内容保持不变
}

这种方式会在JSON中新增@class字段存储类路径,若无需类型信息,直接移除全局的activateDefaultTyping配置是最直接的解决方式。

内容的提问来源于stack exchange,提问作者mtxst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:29:50