I have some enum class, let's imagine
public enum MyEnum {
ONE("one"), TWO("two"), THREE("three"), DEFAULT("some value")
//..
}
and Dto class:
@JsonPropertyOrder(value = {"id", "name", "params"})
public Dto {
private Long id;
private String name;
private Map<MyEnum, Object> params;
}
How can I setup order for keys in params map? I know that LinkedHashMap can be used to setup order and just add to map in proper order. But! There are cases, when key-value should be added in runtime and it should be added to params map not to last link, but inside map. e.g.
params = new LinkedHashMap();
params.put(ONE, new String("object1"));
params.put(THREE, new String("object #3"));
and than in another place of code we just added
params.put(TWO, new Integer(20));
and order inside json should be:
{
"id":"123", "name":"some name",
"params":{"ONE":"object1","TWO":"20","THREE":"object #3"}
}
I can suggest two options that both rely on the fact that Jackson uses a MapSerializer
to serialize objects of type Map
.
First, since enum
types define an implicit natural order based on their declaration order, you can enable your ObjectMapper
's SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS
. The javadoc states,
Feature that determines whether
java.util.Map
entries are first sorted by key before serialization or not: if enabled, additional sorting step is performed if necessary (not necessary forjava.util.SortedMap
s), if disabled, no additional sorting is needed.
In other words, the enums within your params
map will first be sorted by their declaration order and only then serialized. Note that this serialization feature applies to all maps.
Second, you can initialize params
as an EnumMap
. To serialize a Map
, MapSerializer
iterates the map's entrySet()
. The entry set returned by EnumMap#entrySet()
is ordered by the declaration order of the constants in the corresponding enum
type. You'd have
params = new EnumMap<>(MyEnum.class);
params.put(THREE, new String("object #3"));
params.put(ONE, new String("object1"));
// whatever order
and Jackson will serialize them in the order the enum constants are declared.