gpt4 book ai didi

java - 使用 Object 类来表示所有类型的 Json 负载是个好主意

转载 作者:行者123 更新时间:2023-12-05 04:39:57 25 4
gpt4 key购买 nike

我目前在一个代码库中工作,对于每个 REST API 响应,他们都使用如下所示的 java 类

{
Object payload;
List<Error> errors;
String responseStatus;
}

问题是,当我们引用 REST API 的 swagger 文档时,它显示了如下所示的 json 结构。

{
"payload":{},
"errors": [
{
"errMsg":"",
"errCode": ""
}
],
"responseStatus":""

}

因此,如果响应成功,则响应将包含有效载荷,如果出现错误,响应将包含错误列表,响应状态分别设置为成功或失败。

  1. 对错误和成功使用相同的 json 结构是一种好习惯吗?
  2. 有什么方法可以改进 swagger 文档,以便我可以显示特定 API 响应的响应负载 json 的外观。

编辑:我只想提一下,我不能将响应负载更改为任何其他内容,因为它被用于 1000 多个 API 并分布到不同的服务中。

有没有办法至少改进 swagger 文档,而不更改 java 中的 Response Object,因为那艘船已经航行很久了。

最佳答案

  1. 对错误和成功响应使用相同的 json 结构不是一个好的做法。
  2. 是的,如果您可以控制 Swagger 定义,则可以为每个响应代码指定不同的响应。

这是来自 Swagger documentation 的示例

paths:
/users/{id}:
get:
summary: Gets a user by ID.
response:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'401':
$ref: '#/components/responses/Unauthorized'
'404':
$ref: '#/components/responses/NotFound'

# Descriptions of common components
components:
responses:
NotFound:
description: The specified resource was not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Unauthorized:
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/Error'

schemas:
# Schema for error response body
Error:
type: object
properties:
code:
type: string
message:
type: string
required:
- code
- message

# Schema for the User response
User:
type: object
properties:
# Add properties for the User object
# ...

关于java - 使用 Object 类来表示所有类型的 Json 负载是个好主意,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70368656/

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