title: Jackson ObjectMapper: Can java.util.Set be serialized to JSON array in ascending sorted order?
body: <p>I have a Java <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html" rel="nofollow noreferrer"><code>java.util.Set</code></a> of <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html" rel="nofollow noreferrer"><code>Comparable</code></a> types which I would like serialized to a JSON array in ascended sorted order.</p>
  <p>There's an object mapper feature to serialize maps sorted by map keys, but nothing is said about java sets. If I store items in a <code>java.util.Set</code> in my POJO, will the Jackson <code>ObjectMapper</code> serialize them to the JSON array in any kind of order?</p>
  <p>If not, I'm thinking of writing a custom serializer for the set for this purpose - is there a better way that someone can suggest?</p>
  <hr />
  <p>Ultimately, the goal is to deserialize an array of unique integers into some sort of container in a &quot;request&quot; pojo. Then process the request and pass that input field into the corresponding output field (unchanged) in a &quot;response&quot; object.</p>
  <p>I'd like to store the data in the POJOs as <code>java.util.Set&lt;Integer&gt;</code> just to keep all the users happy (if you try to store it as as subtype of <code>Set</code> then consumers of the POJO's interface may be upset that they can't just get a <code>Set</code> but have to expect a <code>HashSet</code> or a <code>TreeSet</code>).</p>
  <p>Will this work?</p>
  <ol>
  <li>JSON array <code>[5,4,3,2,1]</code> is deserialized into <code>Set&lt;Integer&gt;</code> BUT, I use <code>@JsonDeserialize(as=TreeSet.class)</code> on the setter method. So the runtime type of the object is now a <code>TreeSet</code> (even though it's stored in the POJO as a <code>Set</code>).</li>
  <li>The <code>Set</code> is passed around through the server and ultimately ends being stored in the response POJO (runtime type is still <code>TreeSet</code>, even though the POJO field type is Set).</li>
  <li><code>ObjectMapper</code> serializes a <code>TreeSet</code> to JSON array <code>[1,2,3,4,5]</code> (because <code>TreeSet</code> is sorted naturally).</li>
  </ol>
  <p>Item 3 above is the one I'm wondering about - will <code>ObjectMapper</code> use the runtime type of the POJO's field, or the declared type?</p>
  <hr />
  <p>How can I ensure my <code>Set</code> is converted to a JSON array in sorted order?</p>