I have a Java java.util.Set of Comparable types which I would like serialized to a JSON array in ascended sorted order.
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 java.util.Set in my POJO, will the Jackson ObjectMapper serialize them to the JSON array in any kind of order?
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?
Ultimately, the goal is to deserialize an array of unique integers into some sort of container in a "request" pojo. Then process the request and pass that input field into the corresponding output field (unchanged) in a "response" object.
I'd like to store the data in the POJOs as java.util.Set<Integer> just to keep all the users happy (if you try to store it as as subtype of Set then consumers of the POJO's interface may be upset that they can't just get a Set but have to expect a HashSet or a TreeSet).
Will this work?
- JSON array
[5,4,3,2,1]is deserialized intoSet<Integer>BUT, I use@JsonDeserialize(as=TreeSet.class)on the setter method. So the runtime type of the object is now aTreeSet(even though it's stored in the POJO as aSet). - The
Setis passed around through the server and ultimately ends being stored in the response POJO (runtime type is stillTreeSet, even though the POJO field type is Set). ObjectMapperserializes aTreeSetto JSON array[1,2,3,4,5](becauseTreeSetis sorted naturally).
Item 3 above is the one I'm wondering about - will ObjectMapper use the runtime type of the POJO's field, or the declared type?
How can I ensure my Set is converted to a JSON array in sorted order?