简体   繁体   中英

Order of properties in swagger definitions changes from run to run

I use swagger-maven-plugin to generate swagger.json. However, I noticed that an order of properties changes from run to run. For example, it can be:

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

and then after the next generation:

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

My class in Java:

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

It's impossible in Java Runtime to know the exact order of methods declared in a class. If you open java.lang.Class#getDeclaredMethods() (see https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredMethods-- ) you will see that The elements in the returned array are not sorted and are not in any particular order. .

That's why Jackson can't do it for you.

However, there are 2 solutions:

1.You can use @JsonPropertyOrder annotation:

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

2.You can use a class with fields (field order is preserved)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM