我使用 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/