使用
org.openapitools:openapi-generator-maven-plugin
,我注意到在响应中使用由多个对象组成的 allOf
不会生成组合这些多个对象的类。相反,它使用 allOf
部分中定义的第一个类。
这是一个最小的例子(
openapi.yaml
):
openapi: 3.0.0
info:
title: Test
version: v1
paths:
/test:
get:
operationId: get
responses:
'200':
description: Get
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/A'
- $ref: '#/components/schemas/B'
components:
schemas:
A:
type: object
properties:
attA:
type: string
B:
type: object
properties:
attB:
type: integer
通过以下方式在 Java 中生成类时:
mvn org.openapitools:openapi-generator-maven-plugin:5.2.0:generate \
-Dopenapi.generator.maven.plugin.inputSpec=openapi.yaml \
-Dopenapi.generator.maven.plugin.generatorName=java
它显示警告:
[WARNING] allOf with multiple schemas defined. Using only the first one: A
正如预期的那样,它生成了类 A 和 B。但是,当调用
get()
时,调用返回的值是 A
类型:
DefaultApi api = new DefaultApi();
A a = api.get();
相反,我期望一个包含
A
和 B
属性(attA
和 attB
)的复合对象,如下所示(来自 https://editor.swagger.io/ 的结果):
我在 GitHub 上创建了 一个问题,但希望这里有人可能遇到同样的问题并设法解决它。
此外,我无法修改
openapi.yaml
文件,因为它是由我必须调用的API提供的OpenAPI规范,因此修改它没有任何意义,并且如果他们的OpenAPI规范发生变化,管理将变得非常困难时间。
openapi-generator-maven-plugin
的6.0.0版本通过生成由两个对象Get200Response
和A
组成的类(B
)解决了这个问题。使用以下命令生成类后:
mvn org.openapitools:openapi-generator-maven-plugin:6.0.0:generate \
-Dopenapi.generator.maven.plugin.inputSpec=openapi.yaml \
-Dopenapi.generator.maven.plugin.generatorName=java
我可以看到新的
Get200Response
课程:
package org.openapitools.client.model;
// ...
public class Get200Response {
public static final String SERIALIZED_NAME_ATT_A = "attA";
@SerializedName(SERIALIZED_NAME_ATT_A)
private String attA;
public static final String SERIALIZED_NAME_ATT_B = "attB";
@SerializedName(SERIALIZED_NAME_ATT_B)
private Integer attB;
// ...
}
我能够使以下代码工作。在该示例中,我有一个虚拟网络服务器侦听端口
5000
并定义返回 /test
的 {"attA": "hello", "attB": 1}
端点。
package org.example;
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.api.DefaultApi;
import org.openapitools.client.model.Get200Response;
public class Main {
public static void main(String[] args) throws ApiException {
ApiClient apiClient = new ApiClient();
apiClient.setBasePath("http://localhost:5000");
DefaultApi api = new DefaultApi(apiClient);
Get200Response r = api.get();
System.out.println(r.getAttA());
System.out.println(r.getAttB());
}
}
成功打印:
hello
1
仍然不起作用,我有产品和孩子作为移动设备,笔记本电脑,它没有扩展产品的Maven插件,对于Spring