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

如何为swagger-codegen-maven-plugin 3.x生成类添加@JsonIgnoreProperties注解

解决Swagger Codegen 3.x生成类添加@JsonIgnoreProperties的问题

针对Swagger Codegen Maven插件3.0.36版本,你可以通过以下两种方式实现给生成的模型类添加@JsonIgnoreProperties(ignoreUnknown = true)注解:

1. 全局配置(推荐)

直接在插件的configOptions中添加ignoreUnknownProperties=true参数,生成的所有模型类会自动带上该注解。

在pom.xml中的插件配置示例:

<plugin>
    <groupId>io.swagger.codegen.v3</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>3.0.36</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec>
                <language>java</language>
                <configOptions>
                    <!-- 开启全局忽略未知属性 -->
                    <ignoreUnknownProperties>true</ignoreUnknownProperties>
                    <!-- 其他自定义配置 -->
                    <dateLibrary>java8</dateLibrary>
                    <java8>true</java8>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

执行mvn clean generate重新生成代码后,所有模型类会自动添加@JsonIgnoreProperties(ignoreUnknown = true)注解,无需手动修改。

2. 自定义模板(精细化控制)

如果需要仅给特定类添加注解,或者要修改注解的其他属性,可以自定义Mustache模板:

  • 找到Swagger Codegen默认的Java模型模板model.mustache
  • 在类定义上方的注解区域添加@JsonIgnoreProperties(ignoreUnknown = true)
  • 在插件配置中通过templateDirectory指定自定义模板目录:
<configuration>
    <!-- 其他配置 -->
    <templateDirectory>${project.basedir}/src/main/resources/swagger-templates</templateDirectory>
</configuration>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:25:51