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

Spring 6升级后JSON响应出现额外ArrayList和$type字段求助

解决Spring 6升级后JSON响应格式异常问题

问题原因

升级到Spring 6后,Jackson默认序列化配置发生变化,对泛型类型(如ArrayList、LinkedHashMap)会额外输出类型标识("ArrayList"字符串、$type属性),导致JSON格式与Spring 4时期不一致。

解决方案

方案1:通过配置文件修改Jackson序列化规则

如果使用Spring Boot,直接在配置文件中添加以下配置:

application.properties

# 关闭类型信息写入JSON
spring.jackson.serialization.write-type-info-as-property=false
# 可选:保持空值不序列化(和Spring 4行为一致)
spring.jackson.default-property-inclusion=non_null
# 可选:格式化输出JSON(匹配示例格式)
spring.jackson.serialization.indent-output=true

application.yml

spring:
  jackson:
    serialization:
      write-type-info-as-property: false
      indent-output: true
    default-property-inclusion: non_null

方案2:手动配置Jackson ObjectMapper

通过Java配置类自定义ObjectMapper,关闭类型信息序列化:

@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 禁用类型信息作为属性写入JSON
        mapper.disable(SerializationFeature.WRITE_TYPE_INFO_AS_PROPERTY);
        // 空值不序列化
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }
}

方案3:配置Web消息转换器

如果需要更精细控制Web层的消息转换,可配置Jackson2HttpMessageConverter:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2HttpMessageConverter jacksonConverter = new Jackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_TYPE_INFO_AS_PROPERTY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        jacksonConverter.setObjectMapper(objectMapper);
        // 将Jackson转换器放在第一位,确保优先使用
        converters.add(0, jacksonConverter);
    }
}

额外检查点

确认registrarLocatorUtiliy.getRegistrar方法返回的responseMap中,registrationLocator对应的是普通List对象,而非被类型包装的特殊结构。如果工具类中存在手动添加类型标记的逻辑,需移除该逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:17:53