gpt4 book ai didi

java - swagger 定义中的属性顺序因运行而异

转载 作者:行者123 更新时间:2023-12-02 10:55:05 24 4
gpt4 key购买 nike

我使用 swagger-maven-plugin 生成 swagger.json。但是,我注意到属性的顺序在每次运行时都会发生变化。例如,它可以是:

{
...
"definitions" : {
"MyClass1" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"title" : {
"type" : "string"
},
"description" : {
"type" : "string"
},
}
}
}
...
}

然后在下一代之后:

{
...
"definitions" : {
"MyClass1" : {
"type" : "object",
"properties" : {
"description" : {
"type" : "string"
},
"title" : {
"type" : "string"
},
"name" : {
"type" : "string"
}
}
}
}
...
}

我的 Java 类:

public interface MyClass1 {
String getName();
String getTitle();
String getDescription();
}

最佳答案

在 Java 运行时中不可能知道类中声明的方法的确切顺序。如果你打开java.lang.Class#getDeclaredMethods() (参见 https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredMethods-- )您会看到 The elements in the returned array are not sorted and are not in any particular order. .

这就是为什么 jackson 不能为你做这件事。

但是,有两种解决方案:

1.您可以使用@JsonPropertyOrder注释:

@JsonPropertyOrder({"name", "title", "description"})
public interface MyClass1 {
String getName();
String getTitle();
String getDescription();
}

2.您可以使用带有字段的类(保留字段顺序)

public class MyClass1 {
String name;
String title;
String description;
//Getters skipped
}

关于java - swagger 定义中的属性顺序因运行而异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51826241/

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