摇摇欲坠的定义中属性的顺序随运行而变化

时间:2018-08-13 15:53:48

标签: java jackson swagger swagger-maven-plugin

我使用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();
}

1 个答案:

答案 0 :(得分:1)

在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.

这就是杰克逊不能为您做的原因。

但是,有两种解决方案:

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
}