gpt4 book ai didi

rest - JSON 和对象继承

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

我们正在尝试从 SOAP 迁移到 REST,但我们偶然发现了这个问题
这里的聚会可以是个人或组织类型。

示例 XML

<customer>
<details>
<party xsi:type="Individual">
<externalID>ABC123</externalID>
<firstname>John</firstname>
<lastname>Smith</lastname>
</party>
</details>
</customer>

<customer>
<details>
<party xsi:type="Organization">
<externalID>APPLE</externalID>
<organizationName>Apple Inc</organizationName>
<listingName>APPLE</listingName>
</party>
</details>
</customer>

但是当我们转向相同的JSON表示时,我们遇到了继承信息丢失的问题

JSON 示例
{
"customer": {
"details": {
"party": {
"externalID": "ABC123",
"firstname": "John",
"lastname": "Smith"
}
}
}
}

{
"customer": {
"details": {
"party": {
"externalID": "APPLE",
"organizationName": "Apple Inc",
"listingName": "APPLE"
}
}
}
}

因此,当我们使用 Gson 之类的库将 JSON 转换回 Java 对象时,我们失去了个人或组织的定义。

虽然其中一种解决方法是构建额外的服务来检索返回具体类型(个人或组织)的“详细信息”,
有没有其他方法可以在 JSON 中处理这个问题?

最佳答案

自 JSON 模式 v1.0 起,可以使用 oneOf、allOf、anyOf 等关键字组合模式并验证有效负载。

https://spacetelescope.github.io/understanding-json-schema/reference/combining.html

但是,关键字 增强了组合。鉴别器 并入 OpenAPI(前 Swagger)以勉强支持多态。在 OpenAPI 3.0 中,通过添加 增强了这种支持。 oneOf 关键词。

您的继承可以使用 oneOf(用于选择子代之一)和 allOf(用于组合父代和子代)的组合建模。

paths:
/customers:
post:
requestBody:
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/Individual
- $ref: '#/components/schemas/Organization
discriminator:
propertyName: customer_type
responses:
'201':
description: Created
components:
schemas:
Customer:
type: object
required:
- customer_type
- externalID
properties:
customer_type:
type: string
externalID:
type: integer
discriminator:
property_name: customer_type
Individual:
allOf:
- $ref: "#/components/schemas/Customer"
- type: object
- properties:
firtName
type: string
lastName
type: string
Organisation:
allOf:
- $ref: "#/components/schemas/Customer"
- type: object
- properties:
organisationName
type: string
listingName
type: string

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schemaComposition

18/02/2020 编辑:
使用 Jackson 生成 Java 代码, OpenAPITools貌似已经被 PR #5120修复了

关于rest - JSON 和对象继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626716/

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