gpt4 book ai didi

json - 如何在 ResponseEntity 中从 Swagger/OpenAPI 中省略空字段?

转载 作者:行者123 更新时间:2023-12-03 14:32:35 24 4
gpt4 key购买 nike

我试图在我的 ResponseEntity 中省略空值。

我的 Controller 看起来像这样:

@RestController
public class FooController {

//fields
//constructor

@PostMapping
public ResponseEntity<CreateFooResponseV10> createFoo(@Valid @RequestBody CreateFooRequestV10 foo, HttpServletRequest request) {
//some minor logic
return new ResponseEntity<>(aFooResponseV10Builder()
.withFirstName(foo.getFirstName())
.withLastName(foo.getLastName())
.withTestField(NULLABLE_OBJECT)
.build(), ...);
//I generated the builders from the output classes openapi-generator provided
}
// more stuff...
}

NULLABLE_OBJECT等于 null我希望从响应中省略该字段,如下所示:
{
"firstName": "John",
"lastName": "Doe"
}

但我要么得到这些回应,这取决于我到目前为止所尝试的:
{
"firstName": "John",
"lastName": "Doe",
"testField": null
}

或者
{
"firstName": "John",
"lastName": "Doe",
"testField": {"present":false}
}

我使用 openapi-generator 生成我的请求/响应对象( CreateFooResponseV10CreateFooRequestV10 )

这是我的编辑 api.json文件:
{
"openapi": "3.0.1",
"info": { ... },
"servers": [ ... ],
"paths": {
"/foo": {
"post": {
...
"requestBody": {
"description": "Foo to be created",
"content": {
"application/foo+json;version=1.0": {
"schema": {
"$ref": "#/components/schemas/CreateFooRequest_V1_0"
}
}
},
"required": true
},
"responses": {
"201": {
"description": "Foo is successfully created",
"headers": { ... },
"content": {
"application/foo+json": {
"schema": {
"$ref": "#/components/schemas/CreateFooResponse_V1_0"
}
}
}
},
...
}
}
}
},
"components": {
"schemas": {
"CreateFooRequest_V1_0": {
"required": [
"firstName",
"lastName"
],
"type": "object",
"properties": {
"firstName": { ... },
"lastName": { ... },
"testField": {
"description": "...",
"type": "string",
"nullable": true
}
}
},
"CreateFooResponse_V1_0": {
"required": [
"firstName",
"lastName"
],
"type": "object",
"properties": {
"firstName": { ... },
"lastName": { ... },
"testField": {
"description": "...",
"type": "string",
"nullable": true
}
}
}
}
}
}

正如您在请求和响应中看到的 testField不是必需的,可以为空。
所以当 testField 是 null它应该从响应中隐藏,但是当它包含某个日期时,它当然应该显示出来。

我尝试过覆盖 jackson 的 ObjectMapper bean,如 this answer 中所述。 .没用。

我试过添加 spring.jackson.default-property-inclusion=non_nullapplication.properties .没用。

我认为应该添加 @JsonIgnore以上 testField生成的类,但我不知道这是否需要手动完成(对于每个模式组件,生成的东西可能需要大量手动工作)或者是否可以在插件中的某个地方进行配置。

提前致谢。

额外信息

开放API 3.0.1

Maven 3.6.3

Java 11.0.2

jackson 数据绑定(bind)可空 0.2.1

openapi-generator-maven-plugin 4.2.2

最佳答案

您可以在 application.properties 中设置以下内容

spring.jackson.default-property-inclusion = NON_NULL
Customize the Jackson ObjectMapper
注:要使用此功能,您需要 @Autowire ObjectMapper ,而不是手动创建它

关于json - 如何在 ResponseEntity 中从 Swagger/OpenAPI 中省略空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60272220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com