我的请求对象是通过基于json接口文件的openapi-generator-maven-plugin自动生成的。 我想在自动生成的类的属性之一(不是所有类或类的其他属性)之上添加此注释
@JsonInclude(value = JsonInclude.Include.NON_NULL)
以下是自动生成的:
@ApiModel(description = "blabla")
@JsonPropertyOrder({
Request.JSON_PROPERTY_CONSENT_ID,
})
@JsonTypeName("Request")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-02-17T13:14:32.020579400+01:00")
public class Request{
public static final String JSON_PROPERTY_CONSENT_ID = "consentId";
private Long consentId;
@javax.annotation.Nullable
@ApiModelProperty(value = "blabla")
@JsonProperty(JSON_PROPERTY_CONSENT_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getConsentId() {
return consentId;
}
@JsonProperty(JSON_PROPERTY_CONSENT_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setConsentId(Long consentId) {
this.consentId = consentId;
}
所以目前此代码是使用 JsonInclude.Include.USE_DEFAULTS 自动生成的,但我想要 JsonInclude.Include.NOT_NULL。这能实现吗?
我试过使用
spring:
jackson:
default-property-inclusion: NON_NULL
在 application.yml 文件中,但与 USE_DEFAULTS 的结果相同。我正在使用 spring boot 版本 2.1.4
我有类似的问题。我想生成类似于:
的模型类@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
@JsonInclude(JsonInclude.Include.ALWAYS)
private String firstName;
private String middleName;
}
我做了什么:
我使用 openapi-generator-maven-plugin 版本 > 6.0.0 支持添加到规范中的 x-field-extra-annotation:
Person:
type: object
properties:
firstName:
type: string
x-field-extra-annotation: "@JsonInclude(JsonInclude.Include.ALWAYS)"
middleName:
type: string
然后我添加了额外的类注释:
<configOptions>
<additionalModelTypeAnnotations>
<![CDATA[@JsonInclude(JsonInclude.Include.NON_NULL)]]>
</additionalModelTypeAnnotations>
</configOptions>
最后我删除了默认注释:
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>${replacer.version}</version>
<executions>
<execution>
<id>removeUnusedAnnotations</id>
<phase>process-resources</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<includes>
<include>${openapi-generator-maven-plugin.outputBaseDir}/src/**/*.java</include>
</includes>
<replacements>
<replacement>
<token>@JsonInclude\(value = JsonInclude.Include.USE_DEFAULTS\)</token>
<value />
</replacement>
</replacements>
</configuration>
</execution>
</executions>
</plugin>
最后一步是肮脏的解决方法,但找不到更好的方法。
我认为有一个简单的解决方法,只要放
x-field-extra-annotation: "@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)"
在您需要的每个属性中(注意您需要放置完整路径)