温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Use LinkedHashMap instead of HashMap for Swagger dictionary type (Java codegen)?
java openapi swagger swagger-codegen

其他 - 使用LinkedHashMap代替Swagger字典类型(Java codegen)的HashMap吗?

发布于 2020-05-28 11:51:56

我正在使用openapi 3.0.2和codegen插件:

<groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.14</version>

我正在使用此处描述的swagger字典/ hashmap类型:

https://swagger.io/docs/specification/data-models/dictionaries/

openapi: "3.0.2"
...
Labels:
    type: object
    additionalProperties:
        type: string
        minLength: 1
    description:  A description.

当我为此生成Java代码时,它被建模为可扩展的类HashMap

@ApiModel(description = "A description.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-02-26T12:17:36.248Z[Europe/London]")
public class Labels extends HashMap<String, String>  {
...
}

有什么方法可以指示招摇使用a LinkedHashMap而不是a HashMap吗?(而不必从代码生成中排除此类并进行手动修改)。

当我将其返回给客户端时,我想控制此字典中条目的顺序。

查看更多

提问者
Rory
被浏览
19
Rory 2020-03-12 00:27

我使用了一个Maven插件来修改生成的文件:

<plugin>
        <groupId>org.codehaus.gmavenplus</groupId>
        <artifactId>gmavenplus-plugin</artifactId>
        <executions>
                <execution>
                        <id>modify-swagger</id>
                        <phase>generate-sources</phase>
                        <goals>
                                <goal>execute</goal>
                        </goals>
                        <configuration>
                                <properties>
                                        <property>
                                                <name>targetDir</name>
                                                <value>${project.build.directory}</value>
                                        </property>
                                </properties>
                                <scripts>
                                        <script><![CDATA[
                                                def labelsFile = new File(targetDir
                                                                + "/swagger-codegen/src/main/java/com/acme/models/Labels.java")
                                                def labelsFileContents = labelsFile.text
                                                if (labelsFileContents == null) {
                                                        throw Exception();
                                                }

                                                def newLabelsFileContents = labelsFileContents.replaceAll('HashMap', 'LinkedHashMap')
                                                labelsFile.write(newLabelsFileContents)
                                        ]]></script>
                                </scripts>
                        </configuration>
                </execution>
        </executions>
</plugin>