作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 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/
我是一名优秀的程序员,十分优秀!