3

In my Spring Boot rest api, I have the following class:

@Entity
@Table(name="Items")
@JsonPropertyOrder({ "itemId", "description", "viewed" })
public class Item {

    @ApiModelProperty(notes="Id of the item.", required=true, value="100000")
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @JsonProperty(access=Access.READ_ONLY)
    private int itemId = 0;
    @ApiModelProperty(notes="Item description.", required=true, value="Item1")
    @NotNull
    @Size(min=1, max=256)
    private String description;
    private int viewed;

    public int getItemId() {
        return this.itemId;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getViewed() {
        return this.viewed;
    }
}

When I execute the request, the JsonPropertyOrder is respected, however, in the Swagger UI (and the Swagger doc), the properties are listed as description, itemId, viewed. I.e. alphabetical. I never turned on alphabetical sorting, so not sure why its doing that... any way to turn that off? It's doing that to all my classes which are laid out in common sense / logical order...

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
  • Related (or duplicate): [Swagger+Spring: is it possible to preserve the fields order in the payload?](https://stackoverflow.com/q/48949624/113116) – Helen Dec 03 '19 at 08:32

1 Answers1

3

You can define the order in which the properties are going to be shown with ApiModelProperty#position.

Example:

class MyClass {
  @ApiModelProperty(position = 0)
  String myFirstProperty;

  @ApiModelProperty(position = 1)
  String mySecondProperty;
}

It's not the most convenient method, but I couldn't find any other way to achieve this...

Gustavo Passini
  • 2,348
  • 19
  • 25
  • 2
    I just tried it with springfox 3.0.0 and the order is completely ignored. Still sorted alphabetically in swagger-ui. Maybe it is related to the issue https://github.com/springfox/springfox/issues/1280, which they marked as fixed in 2.5.0, but there are a lot of comments that people have the same issue in the later versions, too. You may vote for https://github.com/springfox/springfox/issues/3707. – Honza Zidek Jan 22 '21 at 15:56
  • encountering the same issue with 3.0.0. – yolob 21 Feb 11 '21 at 09:05
  • I'm getting the same with Springfox 3.0.0 – Peter Dec 12 '21 at 18:57
  • 3.0.0 works for me. Also works on class. import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"id", "createdAt", "purchaseId", "orderNumber", "orderStatus", "error", "orderItem"}) public interface OrderContract { Long getId(); LocalDateTime getCreatedAt(); Long getPurchaseId(); String getOrderNumber(); String getOrderStatus(); } – Strauteka Oct 18 '22 at 07:20