在Swagger JSON示例中包含根元素

uinbv5nw  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(120)

在我们的REST API中,我们支持XML和JSON作为输入/输出格式,在生成Swagger文档时,Swagger生成的示例输入不会显示JSON输入的根节点值,但会显示XML示例。
由于我们的REST API也需要JSON的根节点,我如何让Swagger在示例中显示根节点?
Swagger示例XML -

<Request>
    <EmployeeNumber>string</EmployeeNumber>
    <Department>
            <DepartmentId>string</DepartmentId>
            <DepartmentName>string</DepartmentName>
            <DepartmentHead>string</DepartmentHead>
            <DepartmentLocation>string</DepartmentLocation>
    </Department>
</Request>

Swagger示例JSON -

{
    "EmployeeNumber": "string",
    "Department": {
      "DepartmentId": "string",
      "DepartmentName": "string",
      "DepartmentHead": "string",
      "DepartmentLocation": "string"
    }
  }

应为JSON示例-

{
  "Request": {
    "EmployeeNumber": "string",
    "Department": {
      "DepartmentId": "string",
      "DepartmentName": "string",
      "DepartmentHead": "string",
      "DepartmentLocation": "string"
    }
  }
}

如何在swagger注解中提供示例样本,而不是自动生成一个?

cqoc49vn

cqoc49vn1#

我在使用openApi swagger时也遇到了同样的问题。我通过添加一个OpenApiCustomiser解决了这个问题:

@Bean
public OpenApiCustomiser addCustomOpenAPI() {
    return (OpenAPI openApi) -> {
        Map<String, Schema> definitions = openApi.getComponents().getSchemas();
        definitions.entrySet().stream().forEach(e -> {
            Schema schema = e.getValue();
            Example example = ExampleBuilder.fromSchema(schema, definitions);
            SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
            Json.mapper().registerModule(simpleModule);
            String finalExample = new StringBuilder().append("{\"").append(e.getKey())
                    .append("\":").append(Json.pretty(example)).append("}").toString();
            schema.setExample(finalExample);
            openApi.getComponents().getSchemas().put(e.getKey(), schema);
        });
    };
}

ExampleBuilder的Maven依赖项:

<dependency>
        <groupId>org.mock-server</groupId>
        <artifactId>mockserver-core</artifactId>
        <version>5.14.0</version>
    </dependency>

结果真是太棒了,我得到了我所需要的。如果你正在使用swagger,我建议你转移到OpenApi。

{
"UserDTO": {
  "userId": "string",
  "userName": "string",
  "login": "string",
  "password": "string"
}}

相关问题