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

Java Api First模式下服务端响应如何忽略Null字段

解决Api First模式下Java服务端响应过滤Null字段的问题

方案1:修改OpenAPI配置,让生成的DTO自动带Null过滤注解

由于DTO是自动生成的,直接修改代码不可行,可通过OpenAPI的生成规则配置,让生成器自动给DTO添加@JsonInclude(NON_NULL)注解:

给单个Schema添加局部注解

在YAML的目标Schema中加入x-codegen-annotations配置:

components:
  schemas:
    OrderItem:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        discount:
          type: number
      x-codegen-annotations:
        - "@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)"

全局配置所有生成的DTO

如果使用Maven插件生成代码,在插件参数中添加全局规则:

<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>6.6.0</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/resources/openapi.yml</inputSpec>
        <generatorName>spring</generatorName>
        <configOptions>
          <!-- 全局设置所有DTO的Null字段过滤规则 -->
          <jsonInclude>NON_NULL</jsonInclude>
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

Gradle用户可在插件配置中添加configOptions = [jsonInclude: "NON_NULL"]。

方案2:修正Spring全局Jackson配置

如果之前的全局配置未生效,检查以下正确配置方式:

通过application.yml配置

spring:
  jackson:
    default-property-inclusion: non_null

⚠️ 注意:如果生成的DTO上自带@JsonInclude(Include.ALWAYS)注解,会覆盖全局配置,此时优先用方案1调整生成规则。

通过配置类自定义ObjectMapper

@Configuration
public class JacksonGlobalConfig {
    @Bean
    public ObjectMapper customObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 设置全局序列化时排除Null字段
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }
}

方案3:自定义Jackson模块强制过滤Null字段

如果上述方案都无效,可通过自定义Jackson模块,强制所有序列化对象排除Null字段(忽略DTO上的局部注解):

@Configuration
public class JacksonNonNullSerializerConfig {
    @Bean
    public Module nonNullSerializationModule() {
        SimpleModule module = new SimpleModule();
        module.setSerializerModifier(new BeanSerializerModifier() {
            @Override
            public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
                return beanProperties.stream()
                        .map(writer -> {
                            // 给每个字段设置Null值时不输出
                            writer.assignNullSerializer(new NullSerializer() {
                                @Override
                                public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                                    // 空实现,不生成Null字段的JSON
                                }
                            });
                            return writer;
                        })
                        .collect(Collectors.toList());
            }
        });
        return module;
    }
}

该方案会保留非空的数组容器,仅过滤数组元素中的Null字段。


内容的提问来源于stack exchange,提问作者Зюбин Владислав

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:55:10