Search code examples
jacksonspring-roohashset

How to order hashset in Jackson? @JsonPropertyOrder did not work


I have two entity, Survey and Information.

Survey Entity:

@RooJavaBean
@RooToString
@RooJpaActiveRecord(table = "information")
@JsonPropertyOrder({ "seq"})
public class Information {

    @NotNull
    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonBackReference
    private Survey survey;

    private int seq;
}

Information Entity:

@RooJavaBean
@RooToString
@RooJpaActiveRecord(table = "survey")
public class Survey {
    @NotNull
    @Size(min = 3, max = 50)
    private String title;  

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="survey")
    @JsonManagedReference
    private Set<Information> informations = new HashSet<Information>();

}

I used jackson to serialize.

What I expect:

{
  "survey" : {
    "title" : "Medical Survey",
    "informations" : [ {
      "id" : 1,
      "seq" : 0,
      "title" : "Name:",
      "version" : 0
    }, {
      "id" : 2,
      "seq" : 1,
      "title" : "Age:",
      "version" : 0
    },  {
      "id" : 3,
      "seq" : 2,
      "title" : "test",
      "version" : 0
    }, {
      "id" : 4,
      "seq" : 3,
      "title" : "test",
      "version" : 0
    } ],
    "id" : 1,
    "version" : 134
  }
}

But what it comes out:

{
  "survey" : {
    "title" : "Medical Survey",
    "informations" : [ {
      "id" : 2,
      "seq" : 1,
      "title" : "Age:",
      "version" : 0
    }, {
      "id" : 4,
      "seq" : 3,
      "title" : "test",
      "version" : 0
    }, {
      "id" : 3,
      "seq" : 2,
      "title" : "test",
      "version" : 0
    }, {
      "id" : 1,
      "seq" : 0,
      "title" : "Name:",
      "version" : 0
    } ],
    "id" : 1,
    "version" : 134
  }
}
  1. I know that using list should be more suitable in this case but Spring Roo cannot support list in scaffold. Therefore, I used HashSet with a seq number in it.
  2. I also know that I can create an array list of Information to be @transient and then clone and sort it in business layer.

But I would like to know if there is any cleaner solution, that is, ordering when serializing. Thanks.


Solution

  • A HashSet cannot be ordered, that's just normal java behavior. What you are looking for instead is a TreeSet. Supply it with a Comparator, or implement Comparable in your information class, and your Json will be ordered.